簡體   English   中英

LEFT JOIN根據某些條件MYSQL過濾某些Null值

[英]LEFT JOIN filter certain Null values based on some condition MYSQL

在mysql中使用某些條件左連接后是否可以過濾某些空值

我的sqlfiddle供參考

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

我想返回特定預訂日期時間的狀態表,我已經添加了日期條件,但返回的其他日期具有狀態的預訂行

是我的表結構錯誤還是他們的解決方案...?

日期的預期輸出2012年12月9日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)

您可以使用“ Group By依據”來執行此操作,但是對於一個表有多個匹配項的情況,您並不清楚要做什么。 您可以結合使用left outer join聯接和inner 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM