简体   繁体   English

根据MySQL中第一个表的结果选择第二个表中的项目

[英]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.

相关问题 MySQL CodeIgniter是否基于第二个表的第一个Select列进行选择 - MySQL CodeIgniter Select or not from second table based on column of first Select 从第一个表中选择所有结果而不与第二个表匹配 - Select all result from first table without matching with second table MySQL - 从第二个表中选择与第一个表匹配的最后一个记录 - MySQL - Select last record from second table matching with first table 将第二个 MySQL 表中的数据添加到第一个表的结果中 - Add data from second MySQL table to the result from the first one 根据第一个ID从第二个表中选择行 - Select Rows From Second Table Based On id From First 从第二个表中选择多个项目 - select multiple items from second table 即使在第二张表中找不到匹配项,也从第一张表中获取结果-MySQL - Get the result from the first table even if no match is found in the second table - MySQL MySQL SELECT全部来自第一个表,并使用第二个表过滤器的特定where子句连接来自第二个表的匹配数据 - MySQL SELECT all from first table and join matched data from second table with specific where clause for second table filter MYSQL:根据值是否在第二张表中获得1或0查询结果在表中 - MYSQL: Getting a 1 or 0 query result in a table based on whether a value is in second table 返回MySQL表中的所有项目,但根据第二个表检查它们是否是最喜欢的项目 - Return all items from MySQL table, but check if they are a favourite item based on second table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM