2011-06-05 70 views
3

我想弄清楚如何在允許可選AND語句的地方有LEFT OUTER JOIN,因爲在查看記錄時該表是可選的。不過,我有一個問題,即不存在的文件,並在WHERE聲明,就像這樣:WHERE語句中的可選AND MySQL

SELECT rec.record_id, 
     rec.record_name, 
     f.file_name, 
     f.file_id 
FROM 
(
    records rec 

    LEFT OUTER JOIN files f ON f.record_id = rec.record_id 
) 
WHERE rec.record_id = 4928 
AND f.file_approved = 1  <-- this is what returns a zero results 

當我刪除AND f.file_approved = 1它返回的記錄,但是當我離開它,它不返回任何記錄。

如果記錄不包含任何文件記錄,它將不會返回任何內容。我需要它來檢查它,如果沒有文件,它應該仍然能夠返回記錄(沒有文件)。

回答

4

嘗試移動的狀態進入連接語句,這樣,它只會在線路連接是否滿足條件

SELECT rec.record_id, 
     rec.record_name, 
     f.file_name, 
     f.file_id 
FROM 
(
    records rec 

    LEFT OUTER JOIN files f ON f.record_id = rec.record_id AND f.file_approved = 1 
) 
WHERE rec.record_id = 4928; 
+0

現在工作。謝謝! – MacMac 2011-06-05 19:03:44

0

如果玉不想強制執行條件,使用或代替

WHERE 
    rec.record_id = 4928 
OR 
    f.file_approved = 1 
+0

這將返回'f.file_approved = 1'的所有記錄,但它應該只返回匹配'record_id'的記錄。 – 2011-06-05 19:01:43