Question

I'm an SQL newbie. sorry. i have 3 tables: services, cities, city_services. i need to get all services that are available in a given city (using city_id) from the city_services table, but also want to grab the service name from the service table - all in one statement. I know i can nest 2 statements and 2 while loops (php) but that seems inefficient.

Do i need a JOIN or a nested sql statement? i Can't wrap my head around this.

Any help or pointing in the right direction would be great!

Thanks.

sndwg

Was it helpful?

Solution

Yes, use a join. For example:

SELECT service.name, city_service.id
FROM City_Services AS city_service
INNER JOIN Services As service ON city_service.service_id = service.service_id
WHERE city_service.city_id = ?

(How you specify the city_id will depend on your database and how you're accessing it. In the above example I'm assuming you're using a parameterized query with unnamed parameters.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top