2016-09-20 64 views
0

我目前在數據庫中有兩個表,我需要從「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 

編輯:提交出來的數據實際上使我意識到發生了什麼事。與要鍵入的內容有一對多的關係。有沒有辦法在一個查詢中獲取所有類型?

+0

你試過只是用的'左JOIN'代替'LEFT OUTER JOIN'? – haliphax

+0

LEFT JOIN和LEFT OUTER JOIN是一樣的...最終顯示數據示例,您的實際結果和預期結果 – scaisEdge

+0

請參閱[什麼是Sqlfiddle以及爲什麼要關心?](http://stackoverflow.com/questions/38899464 )或許可以幫助@scaisEdge或其他人:p – Drew

回答

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

當我這樣做,它返回空 – jppower175

+0

@ jppower175添加不同的查詢返回空? – scaisEdge

+0

我已更新答案 – scaisEdge