假设我们有这个表数据(请参阅末尾的即用请求来创建它):
+--+-----+-----+--------+
|id|name |color|shape |
+--+-----+-----+--------+
|1 |john |blue |square |
|2 |mary |green|square |
|3 |anna |red |triangle|
|4 |bob |blue |square |
|5 |susan|blue |square |
|6 |frank|red |triangle|
+--+-----+-----+--------+
通过此请求,可以按颜色和形状对行进行分组,更重要的是添加聚合信息:
SELECT
GROUP_CONCAT(name) AS names,
color,
shape,
COUNT(*) AS nb_duplicates
FROM temp_users
GROUP BY color, shape;
结果:
+--------------+-----+--------+-------------+
|names |color|shape |nb_duplicates|
+--------------+-----+--------+-------------+
|john,bob,susan|blue |square |3 |
|mary |green|square |1 |
|anna,frank |red |triangle|2 |
+--------------+-----+--------+-------------+
但是如何才能“取消组合”行,以便:
nb_duplicates
和唯一的组id(可能是自动递增的)?+--+-----+-----+--------+-------------+------------------+
|id|name |color|shape |nb_duplicates|duplicate_group_id|
+--+-----+-----+--------+-------------+------------------+
|1 |john |blue |square |3 |1 |
|2 |mary |green|square |1 |2 |
|3 |anna |red |triangle|2 |3 |
|4 |bob |blue |square |3 |1 |
|5 |susan|blue |square |3 |1 |
|6 |frank|red |triangle|2 |3 |
+--+-----+-----+--------+-------------+------------------+
我发现了一个类似的问题Mysql: count, group by Yet return all results,我尝试了这个命题:
SELECT
u.*,
dups.nb_duplicates
FROM temp_users u
INNER JOIN (
SELECT
u2.color,
u2.shape,
COUNT(*) AS nb_duplicates
FROM temp_users u2
GROUP BY color, shape
) AS dups ON u.color = dups.color AND u.shape = dups.shape;
但我从 MySql 收到此错误:
[HY000][1137] 无法重新打开表:'u'
仅适用于那些想要快速重现该表格的人:
DROP TABLE IF EXISTS temp_users;
CREATE TEMPORARY TABLE temp_users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20),
color VARCHAR(20),
shape VARCHAR(20)
);
INSERT INTO temp_users(name, color, shape) VALUES
('john', 'blue', 'square'),
('mary', 'green', 'square'),
('anna', 'red', 'triangle'),
('bob', 'blue', 'square'),
('susan', 'blue', 'square'),
('frank', 'red', 'triangle');