在三个表中使用左连接和连接,如果没有找到记录则返回零

时间:2017-04-04 16:24:24

标签: mysql sql

我还是新来的,如果在我的表中找不到记录但我使用的当前查询不起作用,我试图返回0(零)值, 所以我的数据库中已经简化了3个表格,它们是:

 戏剧:

+------------+--------------+
| theater_id | theater_name |
+------------+--------------+
|          1 | THEATER 1    |
|          2 | THEATER 2    |
+------------+--------------+


2. showtime:

+-------------+-----------+
| showtime_id | showtimes |
+-------------+-----------+
|           1 | 10:00 AM  |
|           2 | 2:00 PM   |
+-------------+-----------+


3.交易:

+----------------+---------+-------------+------------+------------+
| transaction_id | seat_no | showtime_id | theater_id |    date    |
+----------------+---------+-------------+------------+------------+
|              1 | 1A      |           1 |          1 | 2017-04-04 |
|              2 | 2A      |           2 |          2 | 2017-04-04 |
|              3 | 3A      |           1 |          1 | 2017-04-04 |
|              4 | 2A      |           1 |          1 | 2017-04-04 |
+----------------+---------+-------------+------------+------------+


查询我目前正在处理它:

SELECT   CONCAT(theater.theater_name,' ',GROUP_CONCAT(DISTINCT showtime.showtimes SEPARATOR ' ')) as 2into1,
         COALESCE(COUNT(*), 0)
FROM     transaction
         LEFT JOIN theater ON theater.theater_id = transaction.theater_id
         LEFT JOIN showtime ON showtime.showtime_id = transaction.showtime_id
WHERE    transaction.date = "2017-04-04"
GROUP BY theater.theater_id,
         showtime.showtime_id
ORDER BY theater.theater_name


查询结果为:

+--------------------+-----------------------+
|      2into1        | coalesce(count(*), 0) |
+--------------------+-----------------------+
| THEATER 1 10:00 AM |                     3 |
| THEATER 2 2:00 PM  |                     1 |
+--------------------+-----------------------+

我真正想要的是它会给出充满戏剧和播放时间的细节,并且如果在交易中没有找到记录则返回零,我使用concat的原因是我要去制作一些图表,2到1个字段将是X轴,计数(*)将是Y轴AX

+--------------------+-----------------------+
|      2into1        | coalesce(count(*), 0) |
+--------------------+-----------------------+
| THEATER 1 10:00 AM |                     3 |
| THEATER 1 2:00 PM  |                     0 |
| THEATER 2 10:00 AM |                     0 |
| THEATER 2 2:00 PM  |                     1 |
+--------------------+-----------------------+
好吧,我希望你们能理解并帮助我解决这个问题

1 个答案:

答案 0 :(得分:1)

我想你想要在剧院和放映时间之间cross join,然后是左连接:

SELECT CONCAT(th.theater_name, ' ', sh.showtimes) as 2into1,
       COUNT(t.theater_id)
FROM theater th CROSS JOIN
     showtime st LEFT JOIN
     transaction t
     ON th.theater_id = t.theater_id AND
        st.showtime_id = t.showtime_id AND
        t.date = '2017-04-04'
GROUP BY th.theater_id, st.showtime_id
ORDER BY th.theater_name;

注意:

  • showtime_id位于GROUP BY。相关字段不需要GROUP_CONCAT。应该只有一个值。
  • 日期和字符串应使用单引号来分隔值
  • 如果没有匹配的行,
  • COUNT()会返回0COALESCE()是多余的。
  • 由于ON,日期中的条件需要进入LEFT JOIN子句。