2012-06-11 92 views
0


我有如下表結構:如何爲以下情況構建連接查詢?

Item: 
----------------------- 
item_id INT (PRIMARY), 
category_id MEDIUMINT, 
name VARCHAR(40) 

reservation: 
----------------------- 
id INT (PRIMARY), 
item_id INT, 
date DATE, 
slot VARCHAR(50) 

我想用一個表項特定CATEGORY_ID的所有行加盟預約表ON列ITEM_ID WHERE reservation.date =「東西」在要返回查詢。無法保證預訂行將在查詢日期後可用。但是,即使預留行不存在,我也需要從項目表中返回相應category_id的所有行。這如何實現?

問候,
拉維。

回答

0

聽起來像一個left join將適合該法案。如果添加了日期限制的on條款,日期限制將不會從Item過濾掉行。

select * 
from Item i 
left join 
     reservation r 
on  i.item_id = r.item_id 
     and r.date = '2012-06-11' 
where category_id = 42 
0

使用左連接。例如使用SQL Fiddle我想出了:

select * 
from item as i 
left join reservation as r 
    on i.item_id = r.item_id and r.date is not null (where reservation date is set or use r.date = 'date' if you want a specific date) 
where i.category_id = '1' 
相關問題