1

我有三个表(管理员、域、用户),如下所示

  • 'admin'(admin_id, email, domain_id, pass)
  • '域'(domain_id,名称)
  • 'user' (user_id, email, domain_id, pass)

管理员表:

+--------------------------------+         
| 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 查询,有什么办法吗?

4

2 回答 2

2

如果没有 NOT IN 查询,有什么办法吗?

是的,将用户的左连接与管理员一起使用。

如果iduser 和 admin 表中的属性用于确定两条记录是否属于同一用户,那么您的 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

编辑

根据您对问题的更新,由于电子邮件和域由管理员和用户表共享,您应该在这两列上左连接这些表:

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
于 2012-10-27T09:24:58.973 回答
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)
于 2012-10-27T09:25:44.183 回答