MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query [英] MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

查看:97
本文介绍了MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个sql查询,我想在单个查询中插入多行。所以我使用的东西如下:

  $ sql =INSERT INTO beautiful(name,age)
VALUES
('Helen',24),
('Katrina',21),
('Samia',22),
('惠灵',25),
(优美,29);

mysql_query($ sql,$ conn);

问题是当我执行这个查询时,我想检查一个UNIQUE密钥(不是PRIMARY KEY),例如。应该检查名称,如果这样的名称已经存在,则应更新相应的整行,否则插入。



例如,在下面的例子中,如果卡特里娜已经存在于数据库中,则不管字段数如何,整行都应该被更新。再次,如果Samia不存在,应该插入该行。



我以为使用:

  INSERT INTO beautiful(name,age)
VALUES
('Helen',24),
('Katrina',21),
('Samia',22),
('惠灵',25),
('Yumie',29)ON DUPLICATE KEY UPDATE

这是陷阱。我陷入困境,困惑着怎么走。我有一行插入/更新一次。请给我方向。谢谢。

解决方案

使用关键字 VALUES 来引用新值文档)。

  INSERT INTO beautiful(name,age)
VALUES
('Helen',24),
('Katrina ',21),
('Samia',22),
('Hui Ling',25),
('Yumie',29)
ON DUPLICATE KEY UPDATE
age = VALUES (年龄),
...


I have a sql query where I want to insert multiple rows in single query. so I used something like:

$sql = "INSERT INTO beautiful (name, age)
  VALUES
  ('Helen', 24),
  ('Katrina', 21),
  ('Samia', 22),
  ('Hui Ling', 25),
  ('Yumie', 29)";

mysql_query( $sql, $conn );

The problem is when I execute this query, I want to check whether a UNIQUE key (which is not the PRIMARY KEY), for eg. 'name' in above case, should be checked and if such a 'name' already exists, the corresponding whole row should be updated otherwise inserted.

For instance, in below eg., if 'Katrina' is already present in database, the whole row, irrespective of number of fields, should be updated. Again if 'Samia' is not present, the row should be inserted.

I thought of using:

INSERT INTO beautiful (name, age)
      VALUES
      ('Helen', 24),
      ('Katrina', 21),
      ('Samia', 22),
      ('Hui Ling', 25),
      ('Yumie', 29) ON DUPLICATE KEY UPDATE

Here is the trap. I got stuck and confused how to proceed. I have multiple rows to insert/update at a time. Please give me the direction. Thanks.

解决方案

Use keyword VALUES to refer to new values (see documentation).

INSERT INTO beautiful (name, age)
    VALUES
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
ON DUPLICATE KEY UPDATE
    age = VALUES(age),
     ...

这篇关于MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆