reorder results of mysql query php
I run a mysql query that gets specific results from a table. I then want to print these results in two html tables. The first ordered by one column which is already done by pu开发者_开发百科tting ORDER BY into mysql query. But then I want to print the results ordered by a different column. However, I don't want to run a mysql query again as this is too slow.
So to sum up: Is there a way to reorder the results of a mysql query?
(sorry if the question is unclear, it is my first time using the site.)
PHP has some really great sorting functions. I would most likely make a user-defined sorting function and use that with your result set:
http://php.net/manual/en/function.usort.php
Sorting with PHP is generally very fast. Faster than a 2nd query if your result set is not too large.
You can simply reorder the resultset yourself with one of the sorting methods in php. http://php.net/manual/en/array.sorting.php
I assume you would want to use usort()
here: http://php.net/manual/en/function.usort.php
Why not show it just once and use the jQuery Table sort plugin. Also, if you want to show it twice, there is no problem in making the table sortable.
The advantage would be performance increases as you are transferring the sort operation from server side (PHP) to client side (Javascript).
If you really want to use the sorting features in MySQL, as opposed to those in PHP, one option is to write your PHP code to query twice. In your first query:
SELECT id FROM table_name WHERE (whatever) ORDER BY first_criteria
Then in the second query, fetch rows:
WHERE id IN (2,17,388,etc.)
ORDER BY different_column
. . . passing the IDs from your first query into the IN clause, of course.
Not sure whether this would be faster or slower than sorting in PHP. Might be worth testing.
精彩评论