首页 > 数据库 > mysql教程 > 为什么 MySQL 禁止视图的 FROM 子句中的子查询?

为什么 MySQL 禁止视图的 FROM 子句中的子查询?

Patricia Arquette
发布: 2024-12-25 18:55:16
原创
408 人浏览过

Why Does MySQL Prohibit Subqueries in a View's FROM Clause?

“视图的 SELECT 在 FROM 子句中包含子查询”:了解 MySQL 视图约束

MySQL 视图提供了一种简化数据检索的便捷方法通过提供基础表中的定制数据子集。但是,为了确保这些视图的完整性和性能,有一些限制。

其中一个限制是禁止视图的 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)
登录后复制

抛出错误“视图的 SELECT 在 FROM 子句中包含子查询”,因为它包含以下子查询:

(select * from (select credit_usage.client_id, 
                                        sum(credits_used) as credits_used 
                                 from credit_usage 
                                 group by credit_usage.client_id) as t0
)
登录后复制

要解决此问题问题,可以为子查询创建单独的视图。例如,可以创建以下视图:

create view view_credit_orders as 
(select credit_orders.client_id, 
        sum(credit_orders.number_of_credits) as purchased 
 from credit_orders
 where credit_orders.payment_status='Paid'
 group by credit_orders.client_id)

create view view_credit_usage as 
(select credit_usage.client_id, 
        sum(credit_usage.credits_used) as credits_used 
 from credit_usage 
 group by credit_usage.client_id)
登录后复制

创建这些视图后,可以使用以下修改后的查询创建原始视图:

create view view_credit_status as 
(select view_credit_orders.client_id, 
        view_credit_orders.purchased, 
        ifnull(view_credit_usage.credits_used,0) as used 
 from view_credit_orders
 left outer join view_credit_usage 
  on view_credit_orders.client_id = view_credit_usage.client_id)
登录后复制

以上是为什么 MySQL 禁止视图的 FROM 子句中的子查询?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板