union查询功能和查询结构

krugob8w  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(369)

我试图实现的是在一个表中插入值,如果该值不存在于两个额外的表中。

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部分,当我只要求*\u用户名(例如:admin\u username或staff\u username)时,它工作得很好,但当我需要验证电子邮件是否也存在时,它并没有按预期工作。
我是否在使用不正确存在的地方?如果用户名'admin2000'和电子邮件'adminemail@mail.com'存在于表'admin'中,我正在尝试将它插入到'visitor'表中。它插入了它,不应该这样做。

lskq00tm

lskq00tm1#

问题在于 AND 在子查询中。它搜索具有该用户名和电子邮件的行。所以如果你有一个叫 admin2000 ,但使用不同的电子邮件地址,子查询将不会返回该admin,因此将插入新行。
使用 OR 而不是 AND ,问题就会得到解决。

nwlls2ji

nwlls2ji2#

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

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
                     );

相关问题