我有一个订单表,其中包含订单号,客户ID和代理商ID。然后是一个带有id的客户表和一个带有id的代理表。
我需要从代理商ID' a03'中获取所有订单的客户ID。和代理商ID' a05'
现在我试图获取所有客户ID,但只显示来自代理商' a03'的客户ID列表中的客户ID。以及来自代理商的列表' a05'。
链接第二个WHERE IN不起作用。
select customer.cid
from customer
where customer.cid in
(select order1.cid
from order1
inner join agent on order1.aid=agent.aid
where agent.aid="a05")
and
(select order1.cid
from order1
inner join agent on order1.aid=agent.aid
where agent.aid="a03");
答案 0 :(得分:2)
听起来您只想返回为这两个代理商展示的客户。如果是这种情况,那么您可以使用group by:
select c.cid
from customer c
join order1 o on c.cid = o.cid
join agent a on o.aid = a.aid
where a.aid in ('a05','a03')
group by c.cid
having count(distinct a.aid) = 2
答案 1 :(得分:0)
您需要将and
替换为or customer.cid in
:
select customer.cid
from customer
where customer.cid in
(select order1.cid
from order1
inner join agent on order1.aid=agent.aid
where agent.aid="a05")
or customer.cid in
(select order1.cid
from order1
inner join agent on order1.aid=agent.aid
where agent.aid="a03");
或更短的版本:
select customer.cid
from customer
where customer.cid in
(select order1.cid
from order1
inner join agent on order1.aid=agent.aid
where agent.aid="a05" or agent.aid="a03")
答案 2 :(得分:0)
我想你只是想要这个,如果我正确的话就不需要第二个和/ subselect,它只会增加更多的开销。
select customer.cid
from customer
where customer.cid in
(select order1.cid
from order1
inner join agent on order1.aid=agent.aid
where agent.aid="a05" or agent.aid="a03")
答案 3 :(得分:0)
如果您只是想要客户ID,为什么不使用此
select cid from order1 inner join agent on order1.aid = agent.aid where agent.aid in ("a05", "a03");
答案 4 :(得分:0)
让我看看我是否做对了......
SELECT c.cid
FROM customer c
JOIN order1 o1
ON o1.cid = c.cid
JOIN agent a
ON a.aid = o1.aid
WHERE a.aid IN('a05','a03');