UNION 查询功能和查询结构

UNION query functionality and the query structure

我想要实现的是将值插入到 table 中,如果该值不存在于 2 个额外的 table 中。

INSERT INTO visitor(
  visitor_username,
  email,
  PASSWORD
)
SELECT * FROM
(
SELECT
    'admin2000',
    'adminemail@mail.com',
    '123456'
) AS tmp
WHERE NOT EXISTS
(
SELECT
    admin.admin_username,
    admin.email
FROM
    admin AS admin
WHERE
    admin.admin_username = 'admin2000' AND admin.email = 
'adminemail@mail.com'
UNION
SELECT
staff.staff_username,
staff.email
FROM
staff AS staff
WHERE
staff.staff_username = 'admin2000' AND staff.email = 
'adminemail@mail.com'
 )
LIMIT 1

在 WHERE NOT EXIST 部分,当我只询问 *_username(例如:admin_username 或 staff_username)时,它运行良好,但是当我需要验证电子邮件是否也存在时,它会运行未按预期工作。

我是否正确使用了 WHERE NOT EXIST?如果用户名 'admin2000' 和电子邮件 'adminemail@mail.com' 存在于 table 'admin' 并且我试图将其插入 'visitor' table 它插入它它不应该那样做。

您似乎想编写这样的查询:

INSERT INTO visitor (visitor_username, email, PASSWORD)
    SELECT t.*
    FROM (SELECT 'admin2000' as visitor_username, 'adminemail@mail.com' as email, '123456' as PASSWORD
         ) t
    WHERE NOT EXISTS (SELECT 1
                      FROM admin a
                      WHERE a.visitor_username = t.visitor_username AND a.email = t.email
                     )
    UNION 
    SELECT s.staff_username, s.email, ? as password
    FROM staff s
    WHERE s.staff_username = 'admin2000' AND s.email = 
'adminemail@mail.com';

请注意,第二个子查询缺少密码,因此出错。

使用单个查询,这似乎更简洁:

INSERT INTO visitor (visitor_username, email, PASSWORD)
    SELECT t.*
    FROM (SELECT 'admin2000' as visitor_username, 'adminemail@mail.com' as email, '123456' as PASSWORD
         ) t
    WHERE NOT EXISTS (SELECT 1
                      FROM admin a
                      WHERE a.admin_username = t.visitor_username AND a.email = t.email
                     ) AND
          NOT EXISTS (SELECT 1
                      FROM staff s
                      WHERE s.staff_username = t.visitor_username AND s.email = t.email
                     );

问题出在子查询中的 AND。它搜索具有该用户名和该电子邮件的行。因此,如果您有一个名为 admin2000 的管理员,但具有不同的电子邮件地址,则子查询不会返回该管理员,因此将插入新行。

OR代替AND,问题就解决了。