这是查询:
SELECT B.* FROM
(
SELECT color,COUNT(1) occurrences
FROM colortable GROUP BY color
) A LEFT JOIN colortable B USING (color)
ORDER BY A.occurrences DESC,color;
这是示例数据
mysql> use test
Database changed
mysql> DROP TABLE colortable;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE colortable
-> (
-> id int not null auto_increment,
-> color varchar(20),
-> primary key (id)
-> );
Query OK, 0 rows affected (0.05 sec)
mysql> INSERT INTO colortable (color) VALUES
-> ('red'),('green'),('yellow'),
-> ('green'),('green'),('red');
Query OK, 6 rows affected (0.00 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> SELECT * from colortable;
+----+--------+
| id | color |
+----+--------+
| 1 | red |
| 2 | green |
| 3 | yellow |
| 4 | green |
| 5 | green |
| 6 | red |
+----+--------+
6 rows in set (0.00 sec)
mysql>
这是查询的执行:
mysql> SELECT B.* FROM
-> (
-> SELECT color,COUNT(1) occurrences
-> FROM colortable GROUP BY color
-> ) A LEFT JOIN colortable B USING (color)
-> ORDER BY A.occurrences DESC,color;
+------+--------+
| id | color |
+------+--------+
| 2 | green |
| 4 | green |
| 5 | green |
| 6 | red |
| 1 | red |
| 3 | yellow |
+------+--------+
6 rows in set (0.00 sec)
mysql>
试试看 !!!