SQL:带有外键的交叉表到两个不同的表
我有三个表:
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
我的目标是对邮政编码或城市运行查询,并从 zip_code_data 和 location_data 表中获取与其关联的所有数据
例如,如果用户搜索邮政编码,我想从两个表中提取与该邮政编码相关的所有数据。
我的第一个猜测是首先从交叉表中获取外键(x_data,下面的示例),然后使用它们从每个各自的表中获取数据......因为我有点对于新手用户,我不知道执行此操作的最佳方法。
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%'
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 cross 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%'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建内联视图:
或者只是加入位置表:
You could create an inline view:
or just join the locations table:
我正要发帖:
但看起来你已经得到了......
I was about to post:
but it looks like you've already got it...