[英]Select items in second table based on result from first table in MySQL
I have two MySQL tables tableA and tableB. 我有两个MySQL表tableA和tableB。 In tableA I want to select all zip codes and their respective coordinates using the following query:
在tableA中,我想使用以下查询选择所有邮政编码及其各自的坐标:
SELECT zip,lat,lng
FROM tableA
However, I want to create a one to many relationship and select all items in a second table based on the results from the first table. 但是,我想创建一对多关系,并根据第一个表的结果选择第二个表中的所有项目。 For example I want to select a list of all locations in tableB that are in each zip code in tableA.
例如,我想选择tableA中每个邮政编码中tableB中所有位置的列表。 Normally I would try to run a query like the following (assuming the zip code is '00000':
通常,我会尝试运行如下查询(假设邮政编码为“ 00000”:
SELECT locations
FROM tableB
WHERE distanceFormula(tableA.lat,tableA.lng,tableB.lat,tableB.lng) < 50
How can I combine these two queries to run the second query for every result in the first query. 我如何结合这两个查询来为第一个查询中的每个结果运行第二个查询。
Hopefully you should be able to do something like the following: 希望您应该能够执行以下操作:
SELECT A.`zip`, A.`lat`, A.`lng`, B.`location`
FROM `tableA` AS A
CROSS JOIN (
SELECT *
FROM `tableB` AS B
WHERE distanceFormula( A.`lat`, A.`lng`, B.`lat`, B.`lng` ) < 50
) AS B
WHERE A.`zip` = '000000';
My syntax might be slightly incorrect as I haven't done joins like this in MySQL before (I've only done them on MSSQL) 我的语法可能有点不正确,因为我以前没有在MySQL中完成过这样的联接(我只在MSSQL上完成过联接)
You can use subquerys: 您可以使用子查询:
SELECT locations
FROM tableB
WHERE zip IN
(SELECT zip
FROM tableA);
http://www.mysqltutorial.org/mysql-subquery/ http://www.mysqltutorial.org/mysql-subquery/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.