繁体   English   中英

选择一个表的一行,然后选择另一个表的所有行

[英]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选择titlecontent ,然后从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

但是我得到的只是每个标签的TAG1title1 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM