使用sqlite中的单个select更新行上的多个列

Sin*_*chi 6 sql sqlite

在SQLite中,我需要更新相关表的行计数.

下面的查询执行我想要的但是它多次遍历表以获取计数:

UPDATE overallCounts SET
  total = (count(*) FROM widgets WHERE joinId=1234),
  totalC = (count(*) FROM widgets WHERE joinId=1234 AND source=0),
  totalL = (count(*) FROM widgets WHERE joinId=1234 AND source=2),
  iic = (SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END FROM widgets WHERE joinId=1234 AND widgets.source=0),
  il = (SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END FROM widgets WHERE joinId=1234 AND widgets.source=2)
WHERE id=1234
Run Code Online (Sandbox Code Playgroud)

这个查询准确地检索了我想要的内容,但我需要将其输出转换为更新语句:

SELECT
  count(*) as total,
  sum(case when source=0 then 1 else 0 end) as totalC,
  sum(case when source=2 then 1 else 0 end) as totalL,
  case when source=0 then 1 else 0 end as iic,
  case when source=2 then 1 else 0 end as il
FROM widgets
WHERE joinId=1234
Run Code Online (Sandbox Code Playgroud)

小智 8

在给定的语句中,ItemName和ItemCategoryName都在UPDATE的单个语句中更新.它在我的SQLite中工作.

UPDATE Item SET ItemName='Tea powder', ItemCategoryName='Food' WHERE ItemId='1';
Run Code Online (Sandbox Code Playgroud)

  • 这是怎么得到这么多赞的?该问题特别说明“使用单个选择”,但此答案没有 SELECT 子句,只有文字值。 (3认同)

cha*_*cha 6

SQLite不支持UPDATE查询中的JOIN。它是SQLIte的局限性。但是,您仍然可以使用强大的INSERT或REPLACE语法在SQLite中进行操作。这样做的唯一缺点是,您在totalCounts中将始终有一个条目(如果没有条目,则将其插入)。语法为:

INSERT OR REPLACE INTO overallCounts (total, totalC, totalL, iic, il)
SELECT
  count(*) as total,
  sum(case when source=0 then 1 else 0 end) as totalC,
  sum(case when source=2 then 1 else 0 end) as totalL,
  case when source=0 then 1 else 0 end as iic,
  case when source=2 then 1 else 0 end as il
FROM widgets
WHERE joinId=1234
ON CONFLICT REPLACE
Run Code Online (Sandbox Code Playgroud)


小智 6

UPDATE overallCounts SET (total, totalC, totalL, iic, il) =
  (SELECT
    count(*) as total,
    sum(case when source=0 then 1 else 0 end) as totalC,
    sum(case when source=2 then 1 else 0 end) as totalL,
    case when source=0 then 1 else 0 end as iic,
    case when source=2 then 1 else 0 end as il
  FROM widgets
  WHERE joinId=1234)
WHERE joinId=1234;
Run Code Online (Sandbox Code Playgroud)