簡體   English   中英

從具有多個子查詢的 2 個表創建視圖

[英]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;

datecodeevent上添加索引以使其更快。

同樣在您的查詢中,您在total_counter之后缺少逗號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM