Pregunta

Tengo una tabla en mi sitio donde el usuario tiene la capacidad de reordenar las filas. Esta parte es fácil de hacer con jQuery UI, y conseguir la nueva vuelta orden es simple utilizando el método $('#sortable').sortable("serialize"). Mi pregunta ahora es, ¿cuál es la forma más eficiente para salvar a todos estos registros en la base de datos, ya que cambiar el orden de un elemento cambia todos los registros de la tabla? Sé que podría crear una nueva declaración UPDATE para cada fila en función de su identificación, pero siento que tiene que haber una mejor manera. ¿Hay?

Estoy usando MySQL y ASP.NET.

¿Fue útil?

Solución

Use the START TRANSACTION command. This is much faster.

Otros consejos

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!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top