0

I need a SQL solution for the following:

Lets say I have one table named "TRIPS"

[  id ][ Name  ][ Duration]
[  1  ][ Trip1 ][   12    ]
[  2  ][ Trip2 ][   16    ]
[  3  ][ Trip3 ][   5     ] 

And another table with countries each TRIP visits: LOCATIONS

[  tripId ][ country ]
[    1    ][    US   ] <--
[    1    ][    PA   ] <--
[    1    ][    RU   ]
[    2    ][    US   ] <--
[    2    ][    PA   ] <--
[    3    ][    PA   ]
[    3    ][    RU   ]

Now I want all the TRIPS which visitis "US" and "PA". So the result will be 1 and 2 becouse they both visit US and PA.

I thought I could use INNER JOIN but that only takes one row in the LOCATIONS table (afaik)

Can someone help me?

[EDIT]

I have it working with this ugly way:

SELECT * ,group_concat(distinct(LOCATIONS.country) separator ',') as COUNTRYCODES 
FROM TRIPS left join LOCATIONS on TRIPS.id = LOCATIONS.tripid  
group by TRIPS.id 
having COUNTRYCODES like '%PA%' and COUNTRYCODES like '%US%';

But I think using "like" is an ugly solution

1 Answer 1

1
SELECT *, COUNT(DISTINCT tripID) AS cnt
FROM TRIPS
LEFT JOIN LOCATIONS ON TRIPS.id = LOCATIONS.tripID
WHERE LOCATIONS.country IN ('US', 'PA')
GROUP BY TRIPS.id
HAVING cnt = 2

Basically, get all records where the trip was to PA or US, count how many trips were made, and return only those where BOTH countries were visited.

Sign up to request clarification or add additional context in comments.

1 Comment

I cant get it to work. I get only one row with this QUERY with a count of all the rows it finds.So, if it finds 20 rows, the cnt = 20. "SELECT *, COUNT(DISTINCT tripID) AS cnt FROM TRIPS LEFT JOIN LOCATIONS ON TRIPS.id = LOCATIONS.tripID WHERE LOCATIONS.country IN ('US', 'PA')"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.