如果我有这两个表:
[ 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
,然后选择所有tags
来自table2
,其中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
我想要得到的是
标题1
内容1
标签1 标签2 标签3
但我得到的只是 TAG1
和每个标签的 title1 content1
的重复值
然后我尝试了
SELECT a.title, a.content,
(SELECT DISTINCT b.tags)
FROM table1 a LEFT JOIN table2 b
WHERE a.id = 1
但仍然无法按预期工作。
最佳答案
对于 ibtain 与同一行上的 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
对于不同的任务,您可以使用
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
关于mysql - SELECT 一个表的一行,以及另一个表中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44949123/