假设我有这张表:
+-----------+-------+
| name | seat |
+-----------+-------+
| Andrew | 1 |
| Andrew | 5 |
| Andrew | 15 |
| Billy | 2 |
| Billy | 5 |
+-----------+-------+
有没有办法为每个name
SELECT
对应的seat
出现并将它们附加到一行中?
期望的输出:
+-----------+-------+-------+-------+
| name | seat1 | seat2 | seat3 |
+-----------+-------+-------+-------+
| Andrew | 1 | 5 | 15 |
| Billy | 2 | 5 | NULL |
+-----------+-------+-------+-------+
我尝试使用 GROUP
进行简单的 SELECT
:
SELECT `name`, seat
FROM users
GROUP BY `name`
ORDER BY `name`;
但它当然会为每个名字输出 1 列 seat
。
+-----------+-------+
| name | seat |
+-----------+-------+
| Andrew | 1 |
| Billy | 2 |
+-----------+-------+
这可能吗?如何实现?
最佳答案
因为您正在使用group by
您需要聚合功能
group_concat 是您可能必须使用的一个,
select name, group_concat(seat, SEPARATOR ",") from ...
它应该产生类似的东西
+-----------+-------+
| name | seats |
+-----------+-------+
| Andrew | 1,5,15|
| Billy | 2,5 |
+-----------+-------+
确保它是一个单列,其中的所有字符串均由 SEPARATOR 字符串分隔,而不是多个列,但希望这会很有用/可用
否则,您可能需要进行更多字符串操作才能使用多次包含 group_concat(seat, SEPARATOR ",") 并以某种方式解析其中的位置,例如
select SUBSTRING_INDEX(group_concat(seat, SEPARATOR ","), ",",1), SUBSTRING_INDEX(group_concat(seat, SEPARATOR ","), ",",2), SUBSTRING_INDEX(group_concat(seat, SEPARATOR ","), ",",3) from ....
当然,这也不完全是您想要得到的 - 我不知道如何使所选列的数量动态化
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
希望这有帮助
关于MySQL-选择。在行中多次追加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25797470/