简体   繁体   中英

PHP/MySQL sort inside GROUP

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';

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM