MySQL从第三个表连接的两个表中提取内容
问题描述:
我目前在数据库中有两个表,我需要从“content”和“type”中获取信息。这两个表由第三个表名称“typeMembers”链接。这是结构:MySQL从第三个表连接的两个表中提取内容
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();
当这个返回我得到1行中的数据库,而不是内容的每个typeMember。我构造错了什么?
我想数据返回:
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
编辑:提交出来的数据实际上使我意识到发生了什么事。与要键入的内容有一对多的关系。有没有办法在一个查询中获取所有类型?
答
同一行中获取名称,你可以使用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
你试过只是用的'左JOIN'代替'LEFT OUTER JOIN'? – haliphax
LEFT JOIN和LEFT OUTER JOIN是一样的...最终显示数据示例,您的实际结果和预期结果 – scaisEdge
请参阅[什么是Sqlfiddle以及为什么要关心?](http://stackoverflow.com/questions/38899464 )或许可以帮助@scaisEdge或其他人:p – Drew