2012-12-09 108 views
1

是否有可能後左連接使用一些條件在MySQLLEFT基於一些條件MYSQL連接過濾某些Null值

我sqlfiddle參考

http://sqlfiddle.com/#!2/cb03b/1

我想過濾某些空值返回表與他們的狀態爲特定的預訂日期時間我已添加日期條件,但它的狀態返回其他日期的行預訂

是我的表結構是錯誤的或者是他們爲它的解決方案....

預期產出日期十二月09 2012 00:00:00 + 0000

TABLE_ID FLOOR_ID TABLE_STATUS BOOKING_ID   D 
1   1  seated   35  December, 09 2012 00:00:00+0000 
2   1  free   (null) (null) 
3   1  free   (null) (null) 
4   1  free   (null) (null) 
5   1  free   (null) (null) 

但我正在逐漸從預訂表中的其他空

TABLE_ID FLOOR_ID TABLE_STATUS BOOKING_ID D 
    1  1   seated  35 December, 09 2012 00:00:00+0000 
    2  1      (null) (null) 
    2  1      (null) (null) 
    3  1   free  (null) (null) 
    4  1   free  (null) (null) 
    5  1   free  (null) (null) 
+0

你能在這種情況下給出正確的結果嗎? –

回答

1

您可以使用Group By來做到這一點,但在一張表的多個匹配的情況下,您不太清楚您想要什麼。您可以使用left outer joininner join組合忽略無用booking_table行:

Select 
    t.table_id, 
    t.floor_id, 
    coalesce(Max(bt.table_status),'free') as table_status, 
    max(bt.booking_id) as booking_id, 
    max(bt.date) as d 
From 
    ttable as t 
    Left Outer Join (
     Select 
     bt.table_id, 
     bt.table_status, 
     b.booking_id, 
     b.date 
     From 
     booking_table as bt 
      Inner Join 
     booking As b 
      On b.booking_id = bt.booking_id And b.date = '2012-12-09' 
    ) bt On bt.table_id = t.table_id 
Where 
    t.floor_id = 1 
Group By 
    t.table_id, 
    t.floor_id 

你可以使用一個right outer join避免嵌套,但它不是一般建議:

Select 
    t.table_id, 
    t.floor_id, 
    coalesce(Max(bt.table_status),'free') as table_status, 
    max(b.booking_id) as booking_id, 
    max(b.date) as d 
From 
    booking_table as bt 
    Inner Join 
    booking b 
    On b.booking_id = bt.booking_id And b.date = '2012-12-09' 
    Right Outer Join 
    ttable as t 
    On bt.table_id = t.table_id 
Where 
    t.floor_id = 1 
Group By 
    t.table_id, 
    t.floor_id 

http://sqlfiddle.com/#!2/cb03b/20

+0

我想要所有的table_ids狀態,例如,如果我有5個餐廳表,我需要得到給定日期時間的狀態 – fuzionpro

+0

@fuzionpro我想我現在得到你想要的,看到新的例子。 – Laurence

+0

感謝您的解決方案可能是我需要正確學習SQL – fuzionpro