gpt4 book ai didi

MySQL 条件插入

转载 作者:IT老高 更新时间:2023-10-28 12:51:28 25 4
gpt4 key购买 nike

我很难形成条件插入

我有 x_table 列(实例、用户、项目),其中实例 ID 是唯一的。仅当用户还没有给定项目时,我才想插入新行。

例如尝试插入 instance=919191 user=123 item=456

Insert into x_table (instance, user, item) values (919191, 123, 456) 
ONLY IF there are no rows where user=123 and item=456

我们将不胜感激任何正确方向的帮助或指导。

最佳答案

如果您的 DBMS 对执行插入时从哪个表中选择没有施加限制,请尝试:

INSERT INTO x_table(instance, user, item) 
SELECT 919191, 123, 456
FROM dual
WHERE NOT EXISTS (SELECT * FROM x_table
WHERE user = 123
AND item = 456)

在此,dual 是一个只有一行的表(最初在 Oracle 中找到,现在也在 mysql 中)。逻辑是 SELECT 语句生成具有所需值的单行数据,但仅在尚未找到值时。

或者,查看 MERGE 语句。

关于MySQL 条件插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/913841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com