[英]How to update a table with subquery using data from the same table
我想從表中更新一列,而我想放入的數據是使用引用更新表的子查詢進行數學運算的結果。
問題是我想使用上述數學運算中來自同一行的數據更新每一行。
這是示例:
UPDATE licenses as lic SET lic.numSessions = ( select difference from (select ( select (p.numSessions * p.numMonth) as num from products p inner join licenses l on p.idProduct = l.idProduct and l.idpatient = lic.idPatient and l.currentLicense = 1 ) - ( SELECT COUNT(distinct s.idSession) as num FROM sessions s WHERE s.idPatient = lic.idPatient AND s.dateValue >= (select l.dateCreated from licenses l where l.idPatient = lic.idPatient and l.currentLicense = 1) AND s.status = 2 ) as difference ) x );
編輯:
我想要的例子:
“許可證”的每一行都有一個“ idPatient”。 我們稱之為“ X”。
我想查看X進行了多少次會話(例如10次),然后從“ X的”產品的會話總數中減去該數字(例如50次)。 因此,X更新的結果將是:50-10 = 40。
單獨的子查詢可以完美地工作,我的值為50,然后為10,然后當我嘗試減去時,我將值40作為名為“差異”的列。
我遇到的問題是查詢無法在減操作中的第一個子查詢中識別值“ lic.idPatient”:
/* SQL Error (1054): Unknown column 'lic.idPatient' in 'on clause' */
在此先感謝您,很抱歉,我不是母語為英語的人。
你必須這樣寫查詢
UPDATE licenses AS licNew
SET licNew.numSessions =
(
SELECT x.difference FROM
((SELECT
(
SELECT (p.numSessions * p.numMonth) AS num FROM products p
INNER JOIN licenses l ON p.idProduct = l.idProduct AND l.idpatient = lic.idPatient AND l.currentLicense = 1
)
-
(
SELECT COUNT(DISTINCT s.idSession) AS num
FROM sessions s
WHERE s.idPatient = 6361
AND s.dateValue >= (SELECT l.dateCreated FROM licenses l WHERE l.idPatient = 6361 AND l.currentLicense = 1) AND s.status = 2
))
AS difference, lic.idPatient
FROM licenses lic
)
X WHERE licNew.idPatient = x.idPatient
);
通常,您不能修改表並在子查詢中從同一表中選擇。
請參考此鏈接 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.