質問

This question is somewhat about "best practices", but also a search for potential problems. I would like to be able to run an update on multiple fields and assign different values without running multiple queries and not using a super complex query. So, what I've done is created a table with a primary key and the "name" column as a unique key.

Now, when I want to update multiple columns with different values, I can run a query like this:

INSERT INTO my_table (name, description) VALUES ('name', 'mydescription'), ('name2', 'description2') ON DUPLICATE KEY UPDATE description = VALUES(description)

Is this a bad idea? Is there a better way to do this? Are the standards police going to come arrest me?


Edit: I did just notice one potential issue with this, being a race condition. If one user removes a row while another user is editing it and they save the information, the edit will recreate the row. (Which could be used as a feature or a bug.)

役に立ちましたか?

解決

Further to my comment above (linking to a question where another poster advises of the performance impact from using INSERT ... ON DUPLICATE KEY UPDATE where the records are known to exist), one could use the multiple-table UPDATE syntax with a table materialised from constants using UNION:

UPDATE my_table JOIN (
    SELECT 'name' AS name, 'mydescription' AS description
  UNION ALL
    SELECT 'name2', 'description2'
) t USING (name) SET my_table.description = t.description
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top