向表中插入额外的不需要的行

时间:2015-06-06 13:24:48

标签: mysql

为什么在MYSQL中通过执行此SQL查询2行会添加到表中?此查询是执行两次!?;

INSERT INTO user(`usr_name`, `email`, `name`, `reg_date`, `role_id`)
(
SELECT  "editor1", 
        "editor1@example.com",
        "editor1",
        "2005-12-20",
        2
FROM `user` 
WHERE (("admin", 3) IN (
        SELECT usr_name, role_id
        FROM `user`
    )
    AND NOT EXISTS (
        SELECT usr_name, email
        FROM `user`
        WHERE usr_name = "editor1" OR email = "editor1@example.com"
    ))
)

结果is here!

1 个答案:

答案 0 :(得分:1)

显然,user中的两行符合WHERE条件。

您没有在第一个user中使用FROM表。那么怎么样呢:

INSERT INTO user(`usr_name`, `email`, `name`, `reg_date`, `role_id`)
    SELECT t.*
    FROM (SELECT 'editor1' as user_name, 'editor1@example.com as email,
                 'editor1' as name, '2005-12-20 as reg_date, 2 as role_id
         ) t
    WHERE ('admin', 3) IN (SELECT usr_name, role_id
                           FROM `user`
                          ) AND
          NOT EXISTS (SELECT usr_name, email
                      FROM `user` u
                      WHERE u.usr_name = t.usr_name OR u.email = t.email
                     )

或者,更好的是,但是您不希望在表中重复的字段上有唯一索引:

create unique index idx_user_username on user(usr_name);
create unique index idx_user_email on usr(email);

让数据库保护表。它可以帮到你。