2017-04-04 51 views
0

我在這裏仍然是新的,並且如果在我的表中沒有找到記錄但我當前使用的查詢正在嘗試返回0(零)不工作, 所以有,我已經在我的數據庫簡化了3個表那就是:

1.劇場:
在三個表中使用左連接和concat,如果沒有找到記錄,則返回零

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


2.欣欣:

+-------------+-----------+ 
| 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 | 
+--------------------+-----------------------+ 

我真正想要的是它會給出充分的劇院和showtime細節,並且如果在交易中沒有找到記錄,則返回零,我使用concat的原因是我要製作一些圖表,將2分成1個字段X軸和COUNT(*),將Y軸

+--------------------+-----------------------+ 
|  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

我想你想的劇院和放映時間之間的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()是多餘的。
  • 由於LEFT JOIN,日期條件需要進入ON條款。
+0

我來試試,感謝您的resposne –

+0

已經與烏爾查詢建議做了,但它給每一個2into1字段對事務表 –

+0

沒有記錄它現在解決了值1,而不是0,我是將計(*)到COUNT(t.fieldname), 感謝您的幫助 –

相關問題