我有一个数据库表,其中包含学校和名称列表:
school name point ------------------------ first dani good first dani precise third John nice first dani pro third John cute
我想最终只为每个学校/名称组合记录一条记录并合并点值如下:
school name point -------------------------------------- first dani good and precise and pro third John cute and nice
答案 0 :(得分:3)
您可以像这样使用GROUP_CONCAT
来获得结果:
SELECT school, name, GROUP_CONCAT(point SEPARATOR ' and ') points
FROM table
GROUP BY school, name
如果没关系,你想用结果替换你的实际表格, 例如,使用另一个名称tmptable创建相同的表。
INSERT INTO tmptable
SELECT school, name, GROUP_CONCAT(point SEPARATOR ' and ') points
FROM table
GROUP BY school, name;
DROP TABLE table;
RENAME TABLE tmptable TO table;
您可以在sqlfiddle
中看到结果答案 1 :(得分:1)
这是一个适合你的样本
和一个新的DISTINCT
SELECT
school,
`name`,
GROUP_CONCAT( `point` SEPARATOR ' and ')
FROM ( SELECT DISTINCT school,`name`, `point` FROM groupme) AS result
GROUP BY school,`NAME`;
SELECT
school,
`name`,
GROUP_CONCAT( `point` SEPARATOR ' and ')
FROM groupme
GROUP BY school,`name`;
<强>示例强>
MariaDB [mysql]> select * from groupme;
+----+--------+------+---------+
| id | school | name | point |
+----+--------+------+---------+
| 1 | first | dani | good |
| 2 | first | dani | precise |
| 3 | third | John | nice |
| 4 | first | dani | pro |
| 5 | third | John | cute |
+----+--------+------+---------+
5 rows in set (0.01 sec)
MariaDB [mysql]> SELECT school, `name` , GROUP_CONCAT( `point` SEPARATOR ' and ')
-> FROM groupme
-> GROUP BY school,`name`;
+--------+------+------------------------------------------+
| school | name | GROUP_CONCAT( `point` SEPARATOR ' and ') |
+--------+------+------------------------------------------+
| first | dani | good and precise and pro |
| third | John | nice and cute |
+--------+------+------------------------------------------+
2 rows in set (0.00 sec)
MariaDB [mysql]>
答案 2 :(得分:1)
使用@ ebahi的回答:
将查询更改为@fuzzytree:
所述SELECT school, name, GROUP_CONCAT(distinct point SEPARATOR ' and ') points
FROM table
GROUP BY school, name
sqlfiddle查看结果