I have 3 tables I am trying to query, with one table that links the other two. The tables are CITY, SITE, and ACTIVITIES. They contain sites within cities, and then separate activities at each site. Not every site has multiple activities. Within the CITY table, there is STATE_CODE, which I would like to be able to filter on.
CITY links to SITE through CITY_ID
ACTIVITIES links to SITE through SITE_ID
ACTIVITIES does not directly link to CITY at all
I am trying to get a query that returns all sites and activities in a certain state. So for example, if I’m searching for South Dakota I’d want it to return
**ACTIVITY - SITE**
NULL - Mt. Rushmore
NULL - Black Elk
Needles Highway - Custer State Park
Sylvan Lake - Custer State Park
The following code returned the ACTIVITIES and SITE correctly, but I cannot figure out how to then filter this by STATE_CODE. This query just returns ALL activities and sites in the database.
SELECT ACTIVITY_NAME, SITE_NAME
FROM SITE
LEFT JOIN ACTIVITIES A
ON SITE.SITE_ID = A.SITE_ID;
When I figure out how to link CITY, I would also like to SELECT CITY_NAME and STATE_CODE to return.
EDIT: below is how the tables were created
CREATE TABLE CITY (
CITY_ID CHAR(6) PRIMARY KEY,
CITY_NAME CHAR(50) NOT NULL,
STATE_CODE CHAR(2) NOT NULL
);
CREATE TABLE SITE (
SITE_ID CHAR(5) PRIMARY KEY,
SITE_NAME CHAR(100) NOT NULL,
CITY_ID CHAR(6)
);
CREATE TABLE ACTIVITIES (
ACTIVITY_ID CHAR(5) PRIMARY KEY,
ACTIVITY_NAME CHAR(100) NOT NULL,
SITE_ID CHAR(5) NOT NULL
);
3
Answers
OK, I did get the answer I wanted with the following code, but I would love to see if there are any more elegant solutions out there
May be something like this?
To include cities/sites with no activities, you just need to
LEFT JOIN
to activities so that sites with no related activities are still returned:If you want to extend that to include cities with no sites, then you can change the first join to a
LEFT JOIN
also.