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

时间:2013-04-17 22:05:55

标签: 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

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

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

4 个答案:

答案 0 :(得分:11)

在给定语句中,ItemName和ItemCategoryName都在UPDATE的单个语句中更新。它在我的SQLite中有效。

UPDATE Item SET ItemName='Tea powder', ItemCategoryName='Food' WHERE ItemId='1';

答案 1 :(得分:5)

SQLite不支持UPDATE查询中的JOIN。这是SQLIte的设计限制。 但是,您仍然可以使用其强大的INSERT OR REPLACE语法在SQLite中执行此操作。这样做的唯一缺点是你总是在你的overallCounts中有一个条目(如果你没有一个条目,它将被插入)。语法为:

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

答案 2 :(得分:1)

let myLines = "Hello\\nWorld";
console.log(myLines)

答案 3 :(得分:0)

@cha为什么不检查是否存在?

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
AND EXISTS (SELECT joinId FROM overallCounts WHERE joinId=1234)
ON CONFLICT REPLACE