1

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

1 回答 1

1

您可以使用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

您可以使用 aright 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

于 2012-12-09T17:58:22.273 回答