我有三个表(管理员,域名,用户),如下所示
管理员表:
+--------------------------------+
| admin_id | email | domain_id |
+--------------------------------+
| 1 | aaa | 2034 |
| 2 | bbb | 3034 |
| 3 | ccc | 2034 |
+--------------------------------+
用户表
+--------------------------------+
| user_id | email | domain_id |
+--------------------------------+
| 11 | aaa | 2034 |
| 12 | bbb | 3034 |
| 13 | ccc | 2034 |
| 15 | ddd | 2034 |
| 16 | eee | 3034 |
+--------------------------------+
域名表:
+-----------------------+
| domain_id | name |
+-----------------------+
| 2034 | aaa.com |
| 3034 | bbb.com |
+-----------------------+
输出:
+------------+
|ddd@aaa.com |
|eee@bbb.com |
+------------+
所以我想从用户表中获取管理表中没有的记录。
没有NOT IN查询,有没有办法解决这个问题?
答案 0 :(得分:2)
没有NOT IN查询,有没有办法解决这个问题?
是的,使用admin的用户LEFT JOIN。
如果使用user和admin表中的id
属性来确定这两个记录是否属于同一个用户,则LEFT JOIN将在此属性上,如下所示:
SELECT CONCAT(u.email, CONCAT('@', d.name))
FROM
user u
JOIN domain d
ON u.domain_id = d.domain_id
LEFT JOIN admin a
ON u.id = a.id
WHERE
a.id IS NULL
如果单独id
属性不够,并且您还需要domain_id
来确定两个记录属于同一个用户,那么
SELECT CONCAT(u.email, CONCAT('@', d.name))
FROM
user u
JOIN domain d
ON u.domain_id = d.domain_id
LEFT JOIN admin a
ON u.id = a.id AND u.domain_id = a.domain_id
WHERE
a.id IS NULL
修改强>:
根据您对问题的更新,由于电子邮件和域由管理员和用户表共享,您应该在这两列上LEFT JOIN这些表:
SELECT CONCAT(u.email, CONCAT('@', d.name))
FROM
user u
JOIN domain d
ON u.domain_id = d.domain_id
LEFT JOIN admin a
ON u.email = a.email AND u.domain_id = a.domain_id
WHERE
a.email IS NULL
答案 1 :(得分:1)
您可以使用not exists
:
select u1.email+'@'+d1.name
from user u1 join domains d1 on u1.domain_id = d1.domain_id
where not exists
(select 1 from admin where email = u1.email and domain_id = u1.domain_id)