mysql左连接问题

时间:2010-09-11 16:28:08

标签: sql mysql left-join

我有两张桌子,一张是预订房间,另一张是“中间”桌子,用来保存预订房间的日期(因为预订可能有多个非连续日期)。 / p>

它看起来像:

Res_table: id,room_id,owner_id

Res_table_mid: id,res_id,date

res_table_mid中的res_id列引用res_table的id。我需要获得预订的开始和结束日期。

所以查询看起来像这样:

SELECT * FROM res_table a
LEFT JOIN (SELECT min(date) as start_date, res_id FROM res_table_mid) AS min ON a.id = min.res_id
LEFT JOIN (SELECT max(date) as end_date, res_id FROM res_table_mid) AS max ON a.id = max.res_id

这是按预期工作的,除非表是空的或没有结果,在这种情况下它会错误

#1048 - Column 'res_id' cannot be null

有没有办法写这个,以便我得到我需要的数据,但如果没有结果也没有错误?

谢谢!

3 个答案:

答案 0 :(得分:2)

Select id, room_id, owner_id
From Res_table
    Left Join   (
                Select R2.res_id, Min(R2.Date), Max(R2.Date)
                From Res_table_mid As R2
                Group By R2.res_id
                ) As MinMax
            On MinMax.res_Id = Res_table.Id

在原始查询中,派生表均未指示“分组依据”列。相反,你依靠MySQL猜测它应该按res_id分组。如果我不得不下注,我会说这可能是问题的根源。

答案 1 :(得分:0)

SELECT   a.id,
         a.room_id,
         a.owner_id,
         MAX(m.date) AS end_date ,
         MIN(m.date) AS start_date
FROM     res_table a
         LEFT JOIN res_table_mid m
         ON a.id = m.res_id
GROUP BY a.id,
         a.room_id,
         a.owner_id;

答案 2 :(得分:0)

SELECT min(date) AS start_date FROM (
SELECT * FROM res_table a
LEFT JOIN res_table_mid AS b
ON a.id = b.res_id
WHERE a.id = @reservation)

SELECT max(date) AS end_date FROM (
SELECT * FROM res_table a
LEFT JOIN res_table_mid AS b
ON a.id = b.res_id
WHERE a.id = @reservation)