我目前在数据库中有2个表,我需要从中获取信息,"内容"和"键入"。这两个表由第三个表名" typeMembers链接。"这是结构:
Table Content:
id content link date isPublished
1 content 1 link 1 3/13/91 1
2 content 2 link 2 3/18/91 1
3 content 3 link 3 3/22/91 1
Table type:
id name
1 Event
2 Page
3 Test
Table typeMember
id type_id content_id
1 1 1
2 2 1
3 3 1
4 1 2
5 1 3
目前,我将查询设置为:
//using PDO in PHP
q = $dbc->prepare(
"SELECT a.id, a.content,a.date,a.link, c.name
FROM content a
LEFT OUTER JOIN typeMember b
ON b.content_id = a.id
LEFT OUTER JOIN types c
ON b.type_id = c.id
WHERE a.isPublished = 1
ORDER BY a.date DESC"
);
$r = $q->execute();
当返回时,我在数据库中为每个typeMember而不是内容获得1行。我构造错误的是什么?
我希望退回数据:
id content link date name
1 content 1 link 1 3/13/91 Event, Page, Test
2 content 2 link 2 3/18/91 Event
3 content 3 link 3 3/22/91 Event
如何归还
id content link date name
1 content 1 link 1 3/13/91 Event
1 content 1 link 1 3/13/91 Page
1 content 1 link 1 3/13/91 Test
2 content 2 link 2 3/18/91 Event
3 content 3 link 3 3/22/91 Event
编辑:归档数据实际上让我意识到发生了什么。与要输入的内容有1对多的关系。有没有办法在一个查询中获取所有类型?
答案 0 :(得分:2)
要获取同一行中的名称,可以使用group_Concat
SELECT a.id, a.content, a.date, a.link, group_concat(c.name )
FROM content a
LEFT JOIN typeMember b ON b.content_id = a.id
LEFT JOIN types c ON b.type_id = c.id
WHERE a.isPublished = 1
Group by a.id, a.content, a.date, a.link
ORDER BY a.date DESC