如何解决使用多个子查询从2个表创建视图
我有两个桌子
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 |
现在我创建一个VIEW,因为表非常大
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,( 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
后也缺少逗号。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。