MySQL按重复排序在前

Posted

技术标签:

【中文标题】MySQL按重复排序在前【英文标题】:MySQL order by duplicates top first 【发布时间】:2013-04-04 13:35:42 【问题描述】:

我有一个不成熟的问题,就我不是 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

谢谢

【问题讨论】:

【参考方案1】:

"...最常见的重复优先。"

查询,

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
SQLFiddle Demo

输出

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

【讨论】:

谢谢!这非常适合我的要求。我必须做的唯一调整是在外部和内部查询中使用相同的 WHERE 子句,但是您的答案的总体思路作为工作的基线非常有用。【参考方案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

【讨论】:

【参考方案3】:

这里是查询:

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>

试试看!!!

【讨论】:

以上是关于MySQL按重复排序在前的主要内容,如果未能解决你的问题,请参考以下文章

Mysql按聚合排序和限制分组[重复]

mysql按带有数组键的字符串排序[重复]

按 ID 对核心数据进行排序 [重复]

如何在MYSQL中联合多个表[重复]

JS按数组中的“x”对对象进行排序[重复]

MySql数据库,查询数据导出时会出现重复的记录(数据越多越明显)