![](/img/trans.png)
[英]Select results from one table and for each row select all rows that have the same id from another table
[英]SELECT one row of a table, And all rows in another table
如果我有这两个表:
[ id - title - content ]
[ 1 - title1 - content1 ]
[ 2 - title2 - content2 ]
和
[ id - pid - tags ]
[ 1 - 1 - TAG1 ]
[ 2 - 1 - TAG2 ]
[ 3 - 1 - TAG3 ]
[ 4 - 2 - TAG2 ]
现在我想做的是从table1
选择title
和content
,然后从table2
中选择所有tags
,其中b.pid = a.id
所以我的查询是
SELECT a.title, a.content, b.tags
FROM table1 a LEFT JOIN table2 b ON a.id = b.pid
WHERE a.id = 1
我想要得到的是
title1 content1 TAG1 TAG2 TAG3
但是我得到的只是每个标签的TAG1
和title1 content1
重复值
然后我尝试
SELECT a.title, a.content,
(SELECT DISTINCT b.tags)
FROM table1 a LEFT JOIN table2 b
WHERE a.id = 1
但仍然无法按预期工作。
对于在同一行上获取与id相关的标签,您可以使用group_concat
select a.title, a.content, group_concat(b.tags)
from table1 a LEFT JOIN table2 b ON a.id = b.pid
WHERE a.id = 1
group by a.title, a.content
您也可以在同一查询上使用count
select a.title, a.content, group_concat(b.tags), count(*)
from table1 a LEFT JOIN table2 b ON a.id = b.pid
WHERE a.id = 1
group by a.title, a.content
对于独特的TAS,您可以使用
select a.title, a.content, group_concat(distinct b.tags)
from table1 a LEFT JOIN table2 b ON a.id = b.pid
WHERE a.id = 1
group by a.title, a.content
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.