I have problem with my Postgres Query.
I have 3 tables:
1) Carrier
*id
*name
*telephone
*address
*comments
2) Transportlist
*id
*name
3) Carrier_transport
*id
*carrier_id
*transport_list_id
For Example:
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
I have to select only carriers which have transportlist Car AND Tir
I tried like:
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
But this solution is wrong.
Could somebody can help me?
HAVING COUNT(distinct ct.transport_list_id)>=2carrier_idandtransport_list_idshould be unique incarrier_transport. You select all records withtransport_list_id1 and 2 per carrier_id from the table and count if you got two records (i.e. both 1 and 2) for the carrier. What exactly does not work?transport_list_id IN (1,2)). One record => COUNT(*) = 1 => the carrier is not shown (HAVING COUNT(*)>=2). And this is exactly what you want, isn't it?HAVING COUNT(*) = 2(or count a specific id -- it can never be greater than 2 because of yourWHEREpredicate). Also, yourLEFT JOINbecomes anINNERone because of the sameWHEREpredicate. Apart from the obvious syntax error afterSELECT, your query is fine: it should work. What is exactly wrong with it?