2014-10-16 60 views
1

示例表:MySQL的ORDER BY子的出現次數

ID Name 
1 Apple: Color: Yellow 
2 Apple: Color: Red 
3 Grapes: Color: Green 
4 Grapes: Color: Green 
5 Oranges: Color: Orange 
6 Apple: Color: Yellow 
7 Apple: Color: Yellow 

我需要通過降水果數量來訂購吧,不看顏色。我知道桌子本來可以分成水果和顏色,但那是另一回事。

結果應該是這樣的,通過串的數量排序的,「之前的所有第一:」

ID Name 
1 Apple: Color: Yellow 
2 Apple: Color: Red 
6 Apple: Color: Yellow 
7 Apple: Color: Yellow 
3 Grapes: Color: Green 
4 Grapes: Color: Green 
5 Oranges: Color: Orange 

是否有可能在MySQL中,或做我需要做在PHP F中的排序。恩?

回答

2
mysql> SELECT e.* FROM example AS e 
JOIN (
    SELECT SUBSTRING_INDEX(name, ':', 1) AS fruit, count(*) AS count 
    FROM example 
    GROUP BY fruit) AS x 
    ON SUBSTRING_INDEX(e.name, ':', 1) = x.fruit 
ORDER BY x.count DESC, e.id; 

+----+------------------------+ 
| id | name     | 
+----+------------------------+ 
| 1 | Apple: Color: Yellow | 
| 2 | Apple: Color: Red  | 
| 6 | Apple: Color: Yellow | 
| 7 | Apple: Color: Yellow | 
| 3 | Grapes: Color: Green | 
| 4 | Grapes: Color: Green | 
| 5 | Oranges: Color: Orange | 
+----+------------------------+ 
+0

看着你的回答終於讓我明白了這個令人費解的問題。 – 2014-10-16 22:07:36