2015-09-02 80 views
0

我查看了搜索結果,但找不到答案。 如果在houses_availability中沒有匹配的記錄,我需要查看houses_houses中的記錄。 我知道它與IS NULL有關,但所有我tryed失敗。 請幫忙。如果連接表中沒有記錄,則爲mysql結果

SELECT 
    houses_houses.*, 
    houses_availability.from_date 
FROM 
    houses_houses 
LEFT JOIN 
    houses_availability ON houses_houses.sid=houses_availability.housesid 
WHERE 
    houses_availability.from_date>='2015-09-05' 
AND 
    houses_availability.until_date<'2015-09-11' 
ORDER BY houses_houses.sid LIMIT 0, 9 
+0

小點,你是選擇houses_availability.from_date,但你似乎想只包含沒有houses_availability行的行。因此,對於任何返回的行,該字段總是爲NULL。 – Kickstart

回答

0

您檢查在LEFT OUTER NULL加入提交的WHERE子句中: -

SELECT 
    houses_houses.*, 
    houses_availability.from_date 
FROM houses_houses 
LEFT JOIN houses_availability 
ON houses_houses.sid=houses_availability.housesid 
AND houses_availability.from_date>='2015-09-05' 
AND houses_availability.until_date<'2015-09-11' 
WHERE houses_availability.housesid IS NULL 
ORDER BY houses_houses.sid LIMIT 0, 9 

需要注意的是,你不應該檢查任一列從LEFT OUTER在連接表WHERE子句,因爲這會排除連接後的整個行,而不是在連接之前排除LEFT OUTER JOINed表的行。因此,檢查日期範圍ON子句

+0

非常感謝Kickstart。 – user2369818

0

您需要包括你houses_availability標準中加入.. ON子句:

SELECT houses_houses.*, houses_availability.from_date 
FROM houses_houses 
LEFT JOIN houses_availability ON (houses_houses.sid=houses_availability.housesid AND houses_availability.from_date>='2015-09-05' 
    AND houses_availability.until_date<'2015-09-11') 
WHERE 
    houses_availability.housesid is null 
ORDER BY houses_houses.sid LIMIT 0, 9