Is there an easy way to INSERT
a row when it does not exist, or to UPDATE
if it exists, using one MySQL query?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- php PDO::FETCH_ASSOC doesnt detect select after ba
- sqlyog export query result as csv
Yes,
INSERT ... ON DUPLICATE KEY UPDATE
. For example:I know this is an old question, but the Google lead me here recently so I imagine others come here, too.
@chaos is correct: there is the
INSERT ... ON DUPLICATE KEY UPDATE
syntax.However, the original question asked about MySQL specifically, and in MySQL there is the
REPLACE INTO ...
syntax. IMHO, this command is easier and more straightforward to use for upserts. From the manual:Note this is not standard SQL. An example from the manual:
Edit: Just a fair warning that
REPLACE INTO
isn't likeUPDATE
. As the manual says,REPLACE
deletes the row if it exists, then inserts a new one. (Note the funny "2 rows affected" in the example above.) That is, it will replace the values of all columns of an existing record (and not merely update some columns.) The behavior of MySQL'sREPLACE INTO
is much like that of Sqlite'sINSERT OR REPLACE INTO
. See this question for some workarounds if you only want to update a few columns (and not all columns) if the record already exists.