首頁 > 資料庫 > 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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板