[英]Create a view from 2 tables with multiple subquery
我有兩張桌子
table song
| ID | TITLE | AUTOR | CODE |
| 1 | title_1 | autor_1 | 123 |
| 2 | title_2 | autor_2 | 1332 |
| 3 | title_3 | autor_3 | 3434 |
table playlist
| ID | DATE | EVENT |
| 1 | 2020-05-01 | 123 |
| 2 | 2020-05-02 | 3434 |
| 3 | 2020-09-23 | 123 |
現在我創建了一個視圖,因為表非常大
CREATE OR REPLACE VIEW View_song
AS
select c.id, c.title, c.autor, c.code,
( select
count(p.event) from playlist p
where p.event = c.code
) as total_counter
from song c
所以我有一個 VIEW 總歌曲 + 列 total_counter
| ID | TITLE | AUTOR | CODE | total_counter |
| 1 | title_1 | autor_1 | 123 | 2 |
| 2 | title_2 | autor_2 | 1332 | 0 |
| 3 | title_3 | autor_3 | 3434 | 0 |
我想在 VIEW 中添加一列,所以我想在 today_counter 中添加更多列
| ID | TITLE | AUTOR | CODE | total_counter | today_counter |
| 1 | title_1 | autor_1 | 123 | 2 | 0 |
| 2 | title_2 | autor_2 | 1332 | 0 | 0 |
| 3 | title_3 | autor_3 | 3434 | 0 | 1 |
我試試這個查詢
CREATE OR REPLACE VIEW View_song
AS
select c.id, c.title, c.autor, c.code,
( select
count(p.event) from playlist p
where p.event = c.code
) as total_counter
( select
count(p.event) from playlist p
where p.event = c.code AND date = CURDATE()
) as today_counter
from song c
但它不起作用
一次性使用GROUP BY
進行這些計算。
CREATE OR REPLACE VIEW View_song
AS
SELECT
c.id, c.title, c.author, c.code,
COUNT(p.`event`) AS total_counter,
SUM(IF(p.`date` = CURDATE(), 1, 0)) AS today_counter
FROM song c
LEFT JOIN playlist p ON c.`code` = p.`event`
GROUP BY c.id;
在date
、 code
和event
上添加索引以使其更快。
同樣在您的查詢中,您在total_counter
之后缺少逗號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.