按频率排序SQL查询记录

时间:2011-12-11 22:21:37

标签: php mysql sql

有没有办法按照某个值出现在列中的频率来命令从SQL查询中选择的记录?例如:如果有五个记录,其中column ='value1',三个其中column ='value2',两个where column ='value3',有没有办法让结果首先显示'value1',然后'value2' ,最后,'value3'?

2 个答案:

答案 0 :(得分:7)

SELECT   `column`,
         COUNT(`column`) AS `count`
FROM     `table`
GROUP BY `column`
ORDER BY `count` DESC

快速PoC:

mysql> CREATE TABLE `table` (`id` SERIAL, `column` char(6) NOT NULL, KEY `column_idx`(`column`));
Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO `table` (`column`) VALUES ('value1'), ('value1'), ('value1'), ('value1'), ('value1'), ('value2'), ('value2'), ('value2'), ('value3'), ('value3');
Query OK, 10 rows affected (0.00 sec)
Records: 10  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM `table`;
+----+--------+
| id | column |
+----+--------+
|  1 | value1 |
|  2 | value1 |
|  3 | value1 |
|  4 | value1 |
|  5 | value1 |
|  6 | value2 |
|  7 | value2 |
|  8 | value2 |
|  9 | value3 |
| 10 | value3 |
+----+--------+
10 rows in set (0.00 sec)

mysql> SELECT   `column`,
    ->          COUNT(`column`) AS `count`
    -> FROM     `table`
    -> GROUP BY `column`
    -> ORDER BY `count` DESC;
+--------+-------+
| column | count |
+--------+-------+
| value1 |     5 |
| value2 |     3 |
| value3 |     2 |
+--------+-------+
3 rows in set (0.00 sec)

答案 1 :(得分:2)

假设您想要所有行,但按某些列`col`中的值的频率排序,您可以这样做:

CREATE TABLE tbl (id SERIAL, col VARCHAR(16));
-- INSERT so that `id` does not match frequency of values under `col`
INSERT INTO tbl (col) VALUES ('value1'), ('value2'), ('value3'),
                             ('value1'), ('value2'), ('value3'),
                             ('value1'), ('value2'),
                             ('value1'),
                             ('value1');

    SELECT id, tbl.col
      FROM tbl
INNER JOIN (  SELECT col, COUNT(1) AS freq
                FROM tbl
            GROUP BY 1) derived
           USING (col)
  ORDER BY derived.freq DESC;

将产生

+----+--------+
| id | col    |
+----+--------+
|  4 | value1 |  <-- highest incidence
|  7 | value1 |
|  1 | value1 |
|  9 | value1 |
| 10 | value1 |
|  5 | value2 |
|  8 | value2 |
|  2 | value2 |
|  6 | value3 |  <-- lowest incidence
|  3 | value3 |
+----+--------+
10 rows in set (0.00 sec)