Update multiple rows with different values in a single SQL query

前端 未结 6 657
你的背包
你的背包 2020-12-13 09:15

I have a SQLite database with table myTable and columns id, posX, posY. The number of rows changes constantly (might inc

6条回答
  •  时光取名叫无心
    2020-12-13 10:04

    Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

    You could do:

     UPDATE table SET posX=CASE
          WHEN id=id[1] THEN posX[1]
          WHEN id=id[2] THEN posX[2]
          ...
          ELSE posX END, posY = CASE ... END
     WHERE id IN (id[1], id[2], id[3]...);
    

    The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.

    Otherwise, I'd try with indexing on id, or modifying the architecture.

    In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).

提交回复
热议问题