PHP/MySQL sort inside GROUP

半世苍凉 提交于 2019-12-09 18:58:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!