「視圖的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中文網其他相關文章!