问题
I have a case where I have to group results from table by brands and then order by some other column.
I get my brands from an array. The problem is that when I group by brand this group is sorted by ID (inside group). Is there a way to sort (order by) inside group?
Here is my array and mysql query.
$laptop_brands = array("Acer", "Apple", "Dell", "HP-Compaq", "IBM-Lenovo", "Sony", "Toshiba", "ASUS", "Fujitsu", "Gateway");
$get_videos_query = "SELECT * FROM users_video WHERE location = 'location_1' AND brand IN ('" . implode("','", $laptop_brands) . '\') GROUP BY brand ORDER BY FIELD (brand, "Acer", "Apple", "Dell", "HP-Compaq", "IBM-Lenovo", "Sony", "Toshiba", "ASUS", "Fujitsu", "Gateway"), official DESC';
回答1:
SELECT * FROM (SELECT * FROM users_video WHERE location = 'location_1' AND brand IN ('" . implode("','", > $laptop_brands) . '\') GROUP BY brand ) AS P ORDER BY FIELD (brand, "Acer", "Apple", "Dell", "HP-Compaq", "IBM-Lenovo", "Sony", >"Toshiba", "ASUS", "Fujitsu", "Gateway"), official DESC
you can select from your result then order them
回答2:
I've found the solution. Thx everyone for notes and ideas.
So this is the query I've used to get correct result:
$laptop_brands = array("Acer", "Apple", "Dell", "HP-Compaq", "IBM-Lenovo", "Sony", "Toshiba", "ASUS", "Fujitsu", "Gateway");
$query = "SELECT * FROM (SELECT * FROM users_video WHERE location = 'location_1' AND brand IN ('" . implode("','", $laptop_brands) . '\') ORDER BY official DESC) as my_table_tmp GROUP BY brand ORDER BY FIELD (brand, "Acer", "Apple", "Dell", "HP-Compaq", "IBM-Lenovo", "Sony", "Toshiba", "ASUS", "Fujitsu", "Gateway")';
Thx all, especially to morteza kavakebi
来源:https://stackoverflow.com/questions/11813680/php-mysql-sort-inside-group