gpt4 book ai didi

mysql - 如果相关行不存在则插入

转载 作者:行者123 更新时间:2023-11-30 01:14:55 25 4
gpt4 key购买 nike

INSERT IGNORE 不起作用,因为实际上不会出现键冲突。

这用于进度队列。对于一个应用程序,我不希望有两行状态为 S(表示“已启动”)。但是其他应用程序应该能够 - 特别是如果我想强制两个工作项同时发生,我可以。这就是为什么它不是数据库约束。

所以在 SQL 中说“插入不存在的地方”有点棘手。这有效:

insert into user_queue_google
(user_id, status, start_timestamp)
(select 221, 'S', NOW() FROM filter_type
WHERE 221 not in (select user_id from user_queue_google where status = 'S') limit 1);

问题是 filter_type 是一个完全不相关的表,我只知道它很小并且碰巧永远不会为空。如果由于某种原因它是空的,这将会失败。

我可以在不诉诸 SQL 程序中的存储程序或 IF/THEN 逻辑的情况下避免这种非常可怕的黑客攻击吗?

最佳答案

使用系统虚拟表

insert into user_queue_google (user_id, status, start_timestamp)
select 221, 'S', NOW()
from dual
WHERE not exists
(
select user_id
from user_queue_google
where status = 'S'
and user_id = 221
)

You are permitted to specify DUAL as a dummy table name in situations where no tables are referenced

Source

关于mysql - 如果相关行不存在则插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19163212/

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