我正在设计一个堆栈交换软件,并且我有这个查询来检索那些我的客户拥有帐户的帐户名
SELECT TOP (200) account.account_no, account_type.account_type_id, account_type.account_name, customer.first_name
FROM account
INNER JOIN customer ON account.customer_id = customer.customer_id
INNER JOIN account_type ON account.account_type = account_type.account_type_id
WHERE (account.customer_id = 2)
现在我要选择那些我的客户没有帐户的帐户
答案 0 :(得分:1)
您可以将RIGHT JOIN
与WHERE account.customer_id is null
一起使用
SELECT TOP(200) account.account_no,
account_type.account_type_id,
account_type.account_name,
customer.first_name
FROM account
RIGHT JOIN customer
ON account.customer_id = customer.customer_id
INNER JOIN account_type
ON account.account_type = account_type.account_type_id
WHERE account.customer_id is null
答案 1 :(得分:0)
此查询:
select t.account_type_id from account a
inner join account_type t ON a.account_type = t.account_type_id
where a.customer_id = 2
包含要排除的所有account_type_id
。
因此,将它与NOT IN
子句一起使用:
select account_type_id, account_name
from account_type
where account_type_id not in (
select t.account_type_id from account a
inner join account_type t ON a.account_type = t.account_type_id
where a.customer_id = 2
)
答案 2 :(得分:0)
我会使用NOT EXISTS
:
SELECT act.*
FROM account_type act
WHERE NOT EXISTS (SELECT 1
FROM account a
WHERE a.account_type = act.account_type AND
a.customer_id = 2
);
请注意,customer
表不是必需的。