4

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

谢谢

4

3 回答 3

9

“......最常见的重复首先。”

询问,

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 ║
╚════╩════════╝
于 2013-04-04T13:37:11.527 回答
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
于 2013-04-04T13:39:51.473 回答
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>

试试看 !!!

于 2013-04-04T13:53:17.533 回答