如果连接表中没有记录,则mysql结果

时间:2015-09-02 09:00:43

标签: mysql join null records

我看了搜索但找不到答案。 如果在houses_availability中没有匹配的记录,我需要在houses_houses中查看记录。 我知道它与IS NULL有关,但我尝试的都失败了。 请帮忙。

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

2 个答案:

答案 0 :(得分:0)

在WHERE子句中的LEFT OUTER JOINed表中检查NULL: -

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

重要的是要注意,不应该检查WHERE子句中LEFT OUTER JOINed表中的任何列,因为这会在连接之后排除整行,而不是在连接之前排除LEFT OUTER JOINed表行。因此,检查ON子句中的日期范围

答案 1 :(得分:0)

您需要在JOIN .. ON子句中包含您的houses_availability条件:

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