我有两个SQL表。 客户和标记加入customer.id=tag.attach_id
customer
+------+-------------+--------------+
| id | name | email |
| 9 | Alan | alan@me.com |
+------+-------------+--------------+
tag
+------+-------------+--------------+
| id | attach_id | content |
| 1 | 9 | alan-tag |
| 2 | 9 | second-tag |
+------+-------------+--------------+
我想输出这个:
+-------+-----------------+-----------------------+
| name | email | content |
+-------+-----------------+-----------------------+
| alan | alan@me.com | alan-tag, second-tag |
+-------+-----------------+-----------------------+
这是我对SQL的最佳尝试:
SELECT customer.name, customer.email, tag.content
FROM customer
INNER JOIN tag
ON customer.id=tag.attach_id
GROUP BY customer.id,tag.content;
如果不先用PHP等其他语言处理数据,这是否可行?
答案 0 :(得分:1)
是的,您需要按照其他人在评论区域中的建议使用 GROUP_CONCAT ,更具体地说(确切地说)您的查询是
SELECT `name`, email, GROUP_CONCAT(tag.content SEPARATOR ', ') as content
FROM
customer
INNER JOIN tag ON customer.id = tag.attach_id
GROUP BY customer.id
此查询将为您提供您在帖子上显示的确切结果
答案 1 :(得分:0)
如果您使用的是sql
,则可以使用listaggselect c.name,email,listagg(content,',') within group (order by c.name) "content"
from customer c, tag t
where c.id = t.attach_id
group by c.name,email
答案 2 :(得分:0)
使用此:
SELECT customer.name, customer.email, GROUP_CONCAT(tag.content SEPARATOR ', ') as content
FROM customer
INNER JOIN tag
ON customer.id=tag.attach_id
GROUP BY customer.id;