我有这样的'用户'SQL表结构(ID是随机生成的,不是自动递增的):
ID name deleted lastActive
3242 Joe 0 20-6-2012 23:14
2234 Dave 0 20-6-2012 23:13
2342 Simon 1 20-6-2012 23:02
9432 Joe 1 20-6-2012 22:58
可以有多个已删除(已删除= 1)的用户具有相同的名称,但只有1个未删除的用户具有相同的名称(因此添加Simon很好,但Dave不是)。如果在一个SQL查询中没有已经具有相同名称且已删除= 0的记录,我该如何插入?我需要这样的东西:
INSERT INTO users (ID, name) VALUES ($id, $name)
WHERE NOT EXISTS (SELECT 1 FROM users WHERE name = $name AND deleted = 0)
但这不是正确的语法。
答案 0 :(得分:3)
使用
设置LEFT JOIN这是查询
INSERT INTO users (ID,name)
SELECT A.* FROM
(SELECT RAND() ID,'$name' name) A LEFT JOIN
(SELECT name FROM users WHERE name='$name' AND deleted=0) B
USING (name) WHERE B.name IS NULL;
答案 1 :(得分:1)
确保ID是主键或唯一键,并在所有三个ID,名称和已删除列上创建索引。
REPLACE INTO users (ID, name) VALUES ($id, $name)
答案 2 :(得分:0)
INSERT INTO users (ID, name)
SELECT $id, $name WHERE NOT EXISTS (
SELECT 1 FROM users WHERE name = $name AND deleted = 0
)
答案 3 :(得分:0)
INSERT INTO users SELECT '1', 'Bob','','' FROM DUAL WHERE NOT EXISTS(SELECT ID FROM users WHERE name = 'Bob' AND deleted ='0' LIMIT 1)