SQLite:带COUNT子查询的UPDATE语句

时间:2019-02-26 22:57:32

标签: sql sqlite

UPDATE OPERATING_SYSTEM
SET App_Count = 
    (SELECT COUNT(OPERATE.App_ID) AS App_Count 
     FROM OPERATING_SYSTEM , OPERATE WHERE OPERATING_SYSTEM.Name = OPERATE.Operating_System_Name
     GROUP BY OPERATING_SYSTEM.Name);

此子选择为每个记录返回一个总数 enter image description here

但是,当您单独运行查询时,它会为每个记录返回正确的计数。

enter image description here

4 个答案:

答案 0 :(得分:1)

UPDATE语句的工作方式是为目标表中的每一行评估子查询。由于您的子查询与更新没有关联,因此将对其进行一次处理,并将结果放置在每一行中。 您所缺少的是相关性。对于要更新的​​每一行,您要计算该特定名称的计数。尝试类似的东西:

UPDATE OPERATING_SYSTEM
SET App_Count = 
         (
          SELECT COUNT(O.App_ID) 
          FROM OPERATING_SYSTEM AS OS, OPERATE AS O 
          WHERE OS.Name = O.Operating_System_Name 
                AND OS.Name = OPERATING_SYSTEM.Name
         );

答案 1 :(得分:1)

我认为您需要:

UPDATE OPERATING_SYSTEM 
SET App_Count = (
  SELECT COUNT(App_ID) FROM OPERATE WHERE Operating_System_Name = OPERATING_SYSTEM.Name
)

您不需要将子查询连接到表OPERATING_SYSTEM
您需要的计数在表OPERATE

答案 2 :(得分:1)

子查询不应包含与OPERATING_SYSTEM的联接:

UPDATE OPERATING_SYSTEM
SET App_Count =
    (SELECT COUNT(OPERATE.App_ID) AS App_Count
     FROM OPERATE
     WHERE OPERATING_SYSTEM.Name = OPERATE.Operating_System_Name
     GROUP BY OPERATE.Operating_System_Name);

dbfiddle here

答案 3 :(得分:0)

您的UPDATE语句需要一个WHERE子句。您正在将所有行更新为子查询返回的值之一(在本例中为18)。