根据给定日期连接两个表时列出唯一行

时间:2014-08-27 06:38:54

标签: php mysql sql

我有两个表,一个包含预订信息另一个容器产品信息。下订单时,在预订表中创建新记录。我想根据给定日期得到两个表中所有列的组合表。

表:预订

 ------------------------------------------
| booth_number| booking_date |    status   |
|------------------------------------------|
|         1   |  2014-08-15  |    booked   |
|         2   |  2014-09-10  |    booked   |
|         3   |  2014-09-11  |    booked   |
 ------------------------------------------

表:产品

 ---------------------------------------------------
| booth_number|     desc     |    locked   |  type  |
|------------------------------------------|--------|
|         1   | 2 x bottles  |    true     |  booth |
|         2   | 2 x bottles  |             |  booth |
|         3   | 4 x bottles  |             |  booth |
|         4   | 4 x bottles  |             |  booth |
|         5   | 5 x bottles  |             |  booth |
|         6   | 5 x bottles  |             |  booth |
|             |  $20 entry   |             | ticket |
 ---------------------------------------------------

查询后,我希望在请求日期为2014-08-15

时得到如下结果
 -----------------------------------------------------------------------------
| booth_number|     desc     |    locked   |  type  | request_date |  status  |
|------------------------------------------|--------|--------------|----------|
|         1   | 2 x bottles  |    true     |  booth |  2014-08-15  |  booked  |
|         2   | 2 x bottles  |             |  booth |              |          |
|         3   | 4 x bottles  |             |  booth |              |          |
|         4   | 4 x bottles  |             |  booth |              |          |
|         5   | 5 x bottles  |             |  booth |              |          |
|         6   | 5 x bottles  |             |  booth |              |          |
 -----------------------------------------------------------------------------

2 个答案:

答案 0 :(得分:1)

SELECT
      *
FROM products p
      LEFT JOIN bookings b
                  ON p.booth_number = b.booth_number
                        AND booking_date = '2014-08-15'
WHERE p.booth_number IS NOT NULL
ORDER BY p.booth_number
;

如果在某一天预订或未预订,将列出所有展位

答案 1 :(得分:0)

SELECT * FROM products p LEFT OUTER JOIN bookings b ON p.booth_number = b.booth_number where request_date = 'YYYY-MM-DD'