首頁 >資料庫 >mysql教程 >如何解決MySQL的「視圖的SELECT在FROM子句中包含子查詢」錯誤?

如何解決MySQL的「視圖的SELECT在FROM子句中包含子查詢」錯誤?

Patricia Arquette
Patricia Arquette原創
2024-12-27 12:51:09719瀏覽

How to Resolve MySQL's

解決「視圖的SELECT 在FROM 子句中包含子查詢」錯誤

使用包含FROM 子句的查詢建立視圖時子子句的查詢建立視圖時子子句句時,MySQL 可能會遇到錯誤訊息,指出「視圖的SELECT 在FROM 子句中包含子查詢」。此錯誤表示 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
);

此查詢嘗試建立一個名為view_credit_status 的視圖,其中包含FROM 子句中的子查詢。但是,MySQL 會引發「視圖的 SELECT 在 FROM 子句中包含子查詢」錯誤。

解決方案

要解決此問題,解決方法是建立單獨的視圖用於子查詢並從主視圖引用這些視圖。操作方法如下:

  1. 為與積分使用相關的子查詢建立一個名為 temp_view_used_credits 的視圖:
create view temp_view_used_credits as
select credit_usage.client_id, sum(credits_used) as credits_used
from credit_usage
group by credit_usage.client_id;
  1. 建立主視圖view:
create view view_credit_status as
(
  select credit_orders.client_id,
    sum(credit_orders.number_of_credits) as purchased,
    ifnull(temp_view_used_credits.credits_used,0) as used
  from credit_orders
  left outer join temp_view_used_credits on temp_view_used_credits.client_id = credit_orders.client_id
  where credit_orders.payment_status='Paid'
  group by credit_orders.client_id
);

這種方法將子查詢分離到一個單獨的視圖中,允許MySQL在主視圖中引用它,而不會違反限制。

以上是如何解決MySQL的「視圖的SELECT在FROM子句中包含子查詢」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn