Question

I have a table on my site where the user has the ability to re-order the rows. This part is easy to do with jQuery UI, and getting the new order back is simple using the $('#sortable').sortable("serialize") method. My question is now, what's the most efficient way to save all these records in the database, since changing the order of one item changes all the records in the table? I know I could create a new UPDATE statement for each row based on their ID, but I feel like there has to be a better way. Is there?

I'm using MySQL and ASP.NET.

Was it helpful?

Solution

Use the START TRANSACTION command. This is much faster.

OTHER TIPS

Given that there is potentially an arbitrarily large number of rows, I would store the ordering as a text string entry in the user preferences table (assuming you have such a table). Basically, the default would be a null entry (to save on disc space), which would mean that the ordering is unchanged from the ordering in the database, and if the user changes it you could just serialize the order of the rows (i.e., if they had row 15 first, then 19, then 3, you could have 15-19-3) and then just read it out. It's a single update and it scales indefinitely (well, until the length of the text string, but that's pretty doggone big for the mediumtext and longtext types).


I'm leaving the above just in case it's applicable to other people, but for the specific case described below, I think I would consider storing the prefs in a textfile. Given that the ordering is shown to the user anyway, there's no security risk in the prefs being in a plaintext file, and you can rewrite the whole thing very quickly. Given how you described it below, I would use a two-column CSV file, but obviously you could set it up however makes the most sense.

A quick search on file reading speeds led to this comment on the file_get_contents() function, which suggests you may want to pay attention to how large the file will be when considering the method you'll use to access the data in the file. I don't know about writing.

Your question is lacking some clarity at least for me. I imagine you show a couple of entries to which I will refer by ID~rank. For example:

5~1
6~2
7~3
1~4
24~5
2~6

Now you say changing that "the order of one item changes all the records in the table". Is this really necessary in your design? If the user switches the elements with id-s 1 and 24 then you will have the following serialized list:

[5~1],[6~2],[7~3],[24~5],[1~4],[2~6]

Now by iterating this list you can easily determine which rows should be really updated (this one mismatching the natural order of rank).

In my example you should make two update queries instead of six:

update XYZ set rank=4 where id = 24;
update XYZ set rank=5 where id = 1;

Cheers!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top