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

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

Patricia Arquette
Patricia Arquette原创
2024-12-25 18:55:16416浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn