【问题标题】:MySQL Group By ConcatenateMySQL 按连接分组
【发布时间】:2018-07-26 13:47:04
【问题描述】:

我有两个 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)处理数据,这是否可能?

【问题讨论】:

标签: php mysql sql join group-by


【解决方案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

此查询将为您提供您在帖子中发布的确切结果

【讨论】:

  • 谢谢大家。我得到了SELECT tag.attach_id, GROUP_CONCAT(tag.content SEPARATOR ',') FROM tag GROUP BY tag.attach_id;这里的其他帮助,但这是蛋糕上的樱桃。
【解决方案2】:

如果你使用的是sql,你可以使用listagg

select 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

【讨论】:

  • 会给你报错信息,检查你的查询并更新,试试运行看看
  • 谢谢。更新了我的查询..在思考时这是一个错字。 :)
  • LISTAGG 是 Oracle,不是 MySQL,不是吗?
【解决方案3】:

使用这个:

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;

【讨论】:

    猜你喜欢
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多