小编典典

View的SELECT在FROM子句中包含一个子查询

mysql

我有两个表,我需要创建一个视图。这些表是:

credit_orders(id, client_id, number_of_credits, payment_status)
credit_usage(id, client_id, credits_used, date)

我使用以下查询来执行此操作。不带“创建视图”部分的查询运行良好,但带有“创建视图”的查询则显示错误“视图的SELECT在FROM子句中包含子查询”。可能是什么问题和可能的解决方案:

create view view_credit_status as 
(select credit_orders.client_id, 
        sum(credit_orders.number_of_credits) as purchased, 
        ifnull(t1.credits_used,0) as used 
 from credit_orders
 left outer join (select * from (select credit_usage.client_id, 
                                        sum(credits_used) as credits_used 
                                 from credit_usage 
                                 group by credit_usage.client_id) as t0
                  ) as t1 on t1.client_id = credit_orders.client_id
 where credit_orders.payment_status='Paid'
 group by credit_orders.client_id)

阅读 550

收藏
2020-05-17

共1个答案

小编典典

根据文档:

MySQL文档

  • SELECT语句在FROM子句中不能包含子查询。

解决方法是为每个子查询创建一个视图。

然后从您的视图中访问这些视图 view_credit_status

2020-05-17