MySQL INSERT 如果主键值之一不匹配
我想做这样的 MySQL 查询:
if((value1 != dbPrimaryValue1) OR (value2 != dbPrimaryValue2))
INSERT ROW
else
DO NOTHING
让我们尝试一下示例:
CREATE TABLE `tmp` (
`one` int NOT NULL,
`two` int NOT NULL,
`three` int NOT NULL);
ALTER TABLE `tmp`
ADD PRIMARY KEY (`one`, `two`);
INSERT INTO `tmp`
(`one`, `two`, `three`)
VALUES (1,2,3);
INSERT INTO `tmp`
(`one`,`two`,`three`)
VALUES (10,20,30),
(1,999,999),
(999,2,999),
(1,2,999)
ON DUPLICATE KEY
UPDATE `one` = `one`; // or some dummy no-source-drain operation
结果在这里:
select * from tmp;
+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
| 1 | 2 | 3 |
| 10 | 20 | 30 |
| 1 | 999 | 999 |
| 999 | 2 | 999 |
+-----+-----+-------+
您希望得到这样的结果:
select * from tmp;
+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
| 1 | 2 | 3 |
| 10 | 20 | 30 |
+-----+-----+-------+
可以进行此查询吗?我正在使用大量数据和程序进行操作,例如 load ->比较->保存是不可能的。谢谢!
I would like to do MySQL query like this:
if((value1 != dbPrimaryValue1) OR (value2 != dbPrimaryValue2))
INSERT ROW
else
DO NOTHING
Lets try example:
CREATE TABLE `tmp` (
`one` int NOT NULL,
`two` int NOT NULL,
`three` int NOT NULL);
ALTER TABLE `tmp`
ADD PRIMARY KEY (`one`, `two`);
INSERT INTO `tmp`
(`one`, `two`, `three`)
VALUES (1,2,3);
INSERT INTO `tmp`
(`one`,`two`,`three`)
VALUES (10,20,30),
(1,999,999),
(999,2,999),
(1,2,999)
ON DUPLICATE KEY
UPDATE `one` = `one`; // or some dummy no-source-drain operation
Result is here:
select * from tmp;
+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
| 1 | 2 | 3 |
| 10 | 20 | 30 |
| 1 | 999 | 999 |
| 999 | 2 | 999 |
+-----+-----+-------+
U would like to have result like this:
select * from tmp;
+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
| 1 | 2 | 3 |
| 10 | 20 | 30 |
+-----+-----+-------+
Is it possible to make this query? I'm operating with huge data and procedure like load -> compare -> save is not possible. THANKS!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需分别使两个字段唯一即可。例如:
或者通过以下方式添加约束:
Simply make both fields unique separately. For example:
Or add the constraints via:
如果您创建
UNIQUE
键约束,数据库将不允许您自动插入它们。来自 MySQL 论坛:
If you create a
UNIQUE
key constraint, the database will not allow you to insert them automatically.From MySQL forum: