我的Postgres查询有问题。
我有3张桌子:
1) Carrier
*id
*name
*telephone
*address
*comments
2) Transportlist
*id
*name
3) Carrier_transport
*id
*carrier_id
*transport_list_id
例如:
Carrier: Transportlist: Carrier_transport:
ID | name ID | name ID | carrier_id | transport_list_id
1 | ABC 1 | Car 1 | 1 1
2 | XYZ 2 | Tir 2 | 1 2
3 | 111 3 | Plane 3 | 1 3
4 | ferry 4 | 2 1
5 | 3 4
6 | 3 3
7 | 3 2
我必须只选择有传输列表Car AND Tir
的运营商我试过了:
Select FROM Carrier c
LEFT JOIN Carrier_transport ct ON (ct.carrier_id = c.id)
WHERE ct.transport_list_id IN (1,2)
GROUP BY c.id
HAVING COUNT(*)>=2
但这种解决方案是错误的。
有人可以帮助我吗?
答案 0 :(得分:1)
select ct.carrier_id
from
transportlist tl
inner join
carrier_transport ct on ct.transport_list_id = tl.id
where ct.transport_list_id in (1,2)
group by 1
having bool_or(tl.id = 1) and bool_or(tl.id = 2)