Update multiple columns on a row with a single select in sqlite

前端 未结 4 1146
灰色年华
灰色年华 2021-01-11 22:42

In SQLite I need to update row counts of a related table.

The query below does what I want but it walks the table multiple times to get the counts:

U         


        
相关标签:
4条回答
  • 2021-01-11 22:57

    In the given statement, both ItemName and ItemCategoryName are updated in a single statement with UPDATE. It worked in my SQLite.

    UPDATE Item SET ItemName='Tea powder', ItemCategoryName='Food' WHERE ItemId='1';
    
    0 讨论(0)
  • 2021-01-11 23:11
    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;
    
    0 讨论(0)
  • 2021-01-11 23:15

    SQLite does not support JOINs in UPDATE queries. It is a limitation of SQLIte by design. However, you can still do it in SQLite using its powerful INSERT OR REPLACE syntax. The only disadvantage of this is that you will always have an entry in your overallCounts (if you did not have an entry it will be inserted). The syntax will be:

    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
    
    0 讨论(0)
  • 2021-01-11 23:17

    @cha why not check if exists?

    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
    
    0 讨论(0)
提交回复
热议问题