我有两个表,我需要创建一个视图.表格是:
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)
Nonym.. 151
根据文件:
MySQL文档
SELECT语句不能在FROM子句中包含子查询.
您的解决方法是为每个子查询创建一个视图.
然后从视图中访问这些视图 view_credit_status
根据文件:
MySQL文档
SELECT语句不能在FROM子句中包含子查询.
您的解决方法是为每个子查询创建一个视图.
然后从视图中访问这些视图 view_credit_status
create view view_clients_credit_usage as select client_id, sum(credits_used) as credits_used from credit_usage group by client_id 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 view_clients_credit_usage as t1 on t1.client_id = credit_orders.client_id where credit_orders.payment_status='Paid' group by credit_orders.client_id)
由于最近关于视图限制的 MySQL文档说:
在MySQL 5.7.7之前,子查询不能在视图的FROM子句中使用.
这意味着,选择MySQL v5.7.7或更新版本或将现有MySQL实例升级到这样的版本,将完全消除对视图的这种限制.
但是,如果您的当前生产MySQL版本早于v5.7.7,那么删除对视图的此限制应该只是在做出升级决定时评估的标准之一.使用其他答案中描述的变通方法技术可能是一种更可行的解决方案 - 至少在较短的时间内.