SQL: Cross table with foreign keys to two different tables
I have three tables:
zip_code_data
|zipCodeId| primary key
|zipCode| indexed
|other columns...|
location_data
|locationDataId| primary key
|city| indexed
|other columns...|
x_data
|id| primary key
|zipCodeId| foreign key
|locationDataId| foreign key
My goal is to run a query for either zipcode or city, and get all of the data associated with it from the zip_code_data and location_data tables
For example, if a user searches for a zipcode, I want to pull back all of the data associated with that zipcode from both tables. My first guess is to get the foreign keys first from the cros开发者_StackOverflow社区s table (x_data, example below) and then use those to get the data from each respective table... Since i'm somewhat of a novice user I don't know the best way to do this.SELECT x_data.zipCodeId, x_data.locationDataId
FROM x_data
INNER JOIN zip_code_data
ON x_data.zipCodeId=zip_code_data.zipCodeId
WHERE zip_code_data.zipCode LIKE '2322%'
You could create an inline view:
select zips.othercolumn, LOCS.city
from zips
inner join x_data on zips.zip = x_data_zip and zips.zip like .....
left join (
select id, locations.city from locations
where locations.id = x_data.locationid
) as LOCS
or just join the locations table:
left join locations as locs on locs.locationid = x_data.locationid
I was about to post:
SELECT zip.*,loc.*
FROM x_data xref
JOIN zip_code_data zip ON zip.zipCodeId=xref.zipCodeID
JOIN location_Data loc ON loc.locationDataID=xRef.locationDataID
WHERE zip.zipCode LIKE '2322%' or loc.city LIKE '%aaa%'
but it looks like you've already got it...
精彩评论