2016-09-27 154 views
0

如何使用不同的約束條件查詢多個表? 例如,限制結果,以1行從第一個表,但是從第二個讓所有結果,然後通過訂購的唯一ID ASC這些結果。MySQL如何使用不同的約束來查詢多個表?

例如,這樣的事情:

SELECT p.entry_id AS post_id, 
     p.topic AS post_topic, 
     p.body AS post_body, 
     r.reply AS post_reply 
FROM 
#should get only one row 
(SELECT entry_id, topic, body FROM entry_posts WHERE entry_id = {$id} LIMIT 1) AS p 

FULL JOIN 
#should get all rows with this entry_id and order them 
(SELECT reply, FROM entry_replies WHERE entry_id = {$id} ORDER BY id ASC) AS r 

ON p.entry_id = r.entry_id 

在這種情況下,兩個表中有一欄叫entry_id包含相同的值。

+1

單個ResultSet不能與不同列的個別結果;您的查詢要求提供1行子查詢和另一個子查詢的笛卡爾積。你將得到一個副本'p'的單個結果行與來自'r'的每個結果行配對。 – Uueerdo

回答

1
SELECT p.entry_id AS post_id, 
     p.topic AS post_topic, 
     p.body AS post_body, 
     r.reply AS post_reply 
FROM entry_posts p 
LEFT OUTER JOIN entry_replies r ON r.entry_id = p.entry_id 
WHERE p.entry_id = {$id} 
ORDER BY r.id