2017-07-06 113 views
0

的所有行,如果我有这两个表:选择一个表中的一行,而在另一张表

[ id -  title -  content ] 
[ 1 -  title1 -  content1 ] 
[ 2 -  title2 -  content2 ] 

[ id -  pid -  tags ] 
[ 1 -  1 -  TAG1 ] 
[ 2 -  1 -  TAG2 ] 
[ 3 -  1 -  TAG3 ] 
[ 4 -  2 -  TAG2 ] 

现在我想要做的是选择titlecontenttable1然后从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并为每个标签

然后我试图

SELECT a.title, a.content, 
(SELECT DISTINCT b.tags) 
    FROM table1 a LEFT JOIN table2 b 
    WHERE a.id = 1 

title1 content1重复值但仍然无法按预期工作。

+0

你有两个_tables_,而不是_databases_。 – jarlh

+0

@jarlh我“固定”,虽然将代码行更改为块 –

回答

2

对于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 

可以使用数上相同的查询太

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 
+0

以防万一我想为所有标签使用COUNT(),它是否具有相同的特征? –

+0

是的,你可以使用计数(*)tooo ..答案已更新 – scaisEdge

+2

答案已更新..但逐步添加请求是不公平的。一旦答案被正确解决,你应该接受答案,并事后发布一个新的记录良好的问题 – scaisEdge