Mysql

MySQL如何將計數保存到變數中以更新另一列?

  • August 6, 2022

我有一個帶有列的表:

IdNum, NameEmployee, IdInsurance, NameInsurance, num_employees_not_insured

一些員工沒有保險,因此IdInsuranceNameInsurance無效的。

我想計算有多少員工沒有保險,並將其放在最後一列。

我試過了:

UPDATE MajorTable2
SET num_employees_not_insured =
   (SELECT COUNT(*) FROM MajorTable2)
   WHERE 'IdInsurance' IS NULL);

接下來我嘗試“將計算空行的結果保存到變數中”,例如(但我猜單引號中的內容不算作變數):

SELECT COUNT(*) AS 'NULL_values_in_IdInsurance'
FROM `MajorTable2`
WHERE `IdInsurance` IS NULL;

UPDATE MajorTable2
SET num_employees_not_insured = 'NULL_values_in_IdInsurance';

如何修復我的邏輯和語法?我知道一些 Python,但我的 SQL 超級生疏。

這是克服 MySQL 更新限制的一種方法:

WITH T (n) as (
   SELECT count(*) - count(IdInsurance) from MajorTable2
)
update MajorTable2 set num_employees_not_insured = (
   SELECT n from T
);

對 ybercubes 評論的輕微修改是:

UPDATE MajorTable2 AS m 
CROSS JOIN (
   SELECT COUNT(*) - COUNT(IdInsurance) AS cnt 
   FROM MajorTable2
) AS g 
   SET m.num_employees_not_insured = g.cnt;

小提琴

引用自:https://dba.stackexchange.com/questions/315297