LEFT JOIN根据某些条件MYSQL过滤某些Null值

时间:2012-12-09 17:52:50

标签: mysql sql

是否可以使用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)

1 个答案:

答案 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