MySQL重复排序首先排在前面

时间:2013-04-04 13:35:43

标签: mysql sql select

我有一个lammer问题,因为我不是专业的mysql

我有像

这样的字段
   id    color
   1     red
   2     green
   3     yellow
   4     green
   5     green
   6     red

我想按重复进行分组,并且最常重复 所以它应该这样选择:

   id    color
   2     green
   4     green
   5     green
   1     red
   6     red
   3     yellow

感谢

3 个答案:

答案 0 :(得分:8)

  

“......最常重复。”

查询,

SELECT  a.*
FROM    TableName a
        INNER JOIN 
        (
            SELECT  Color, COUNT(*) totalCount
            FROM    TableName
            GROUP   BY Color
        ) b ON  a.Color = b.Color
ORDER   BY b.TotalCount DESC, a.ID ASC

输出

╔════╦════════╗
║ ID ║ COLOR  ║
╠════╬════════╣
║  2 ║ green  ║
║  4 ║ green  ║
║  5 ║ green  ║
║  1 ║ red    ║
║  6 ║ red    ║
║  3 ║ yellow ║
╚════╩════════╝

答案 1 :(得分:2)

SELECT ID, COLOR
FROM MYTABLE A
JOIN
(
SELECT COLOR, COUNT(*) CN
FROM MYTABLE
GROUP BY COLOR
) B
ON B.COLOR = A.COLOR
ORDER BY B.CN, A.ID

答案 2 :(得分:1)

以下是查询:

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>

试一试!!!