[英]SELECT FROM two different tables with the same WHERE clause?
I have two different tables. 我有两个不同的表。 cities_buildings
and map_buildings
. cities_buildings
和map_buildings
。 Both have the EXACT SAME COLUMN names/structure. 这两个有相同的列名/结构。
Is it possible to do something like so, and still have each record from either table by themselves? 是否可以执行类似的操作,并且仍然单独保留每个表中的每个记录?
SELECT cb.city_id,
cb.type,cb.x,
cb.y,
mb.city_id,
mb.type,
mb.x,
mb.y
FROM cities_buildings AS cb,
map_buildings AS mb
WHERE city_id IN (1,2)
Thanks in advance! 提前致谢!
You could do this: 您可以这样做:
SELECT cb.city_id,
cb.type,cb.x,
cb.y,
mb.city_id,
mb.type,
mb.x,
mb.y
FROM cities_buildings AS cb,
map_buildings AS mb
WHERE mb.city_id IN (1,2) AND cb.city_id IN (1,2);
however this is probably better: 但是这可能更好:
SELECT cb.city_id,
cb.type,cb.x,
cb.y,
mb.city_id,
mb.type,
mb.x,
mb.y
FROM cities_buildings AS cb,
map_buildings AS mb
WHERE mb.city_id IN (1,2) AND mb.city=cb.city;
This relates the cities. 这关系到城市。
Alternative (and most used is): 替代方法(最常用的是):
SELECT cb.city_id,
cb.type,cb.x,
cb.y,
mb.city_id,
mb.type,
mb.x,
mb.y
FROM cities_buildings AS cb
LEFT JOIN map_buildings AS mb ON mb.city=cb.city
WHERE mb.city_id IN (1,2);
Not entirely sure what you want to accomplish, but perhaps this will do it: 不确定要完成什么,但是也许可以做到:
SELECT * FROM (
SELECT city_id, type, x, y FROM cities_buildings
UNION ALL
SELECT city_id, type, x, y FROM map_buildings
) WHERE city_id IN (1,2)
This concatenats the tables, and then finds rows with a city_id
of either 1 or 2 from either one of them. 这将连接表,然后从其中任一表中查找city_id
为1或2的行。
If you have duplicates in the tables and don't want duplicates in the output, use UNION
instead of UNION ALL
. 如果表中有重复项,并且不想在输出中重复项,请使用UNION
而不是UNION ALL
。 That will have an performance impact, though. 但是,这将对性能产生影响。
If you want to be able to track what table a row came from, you can change the inner part of the query to this: 如果您希望能够跟踪行来自哪个表,则可以将查询的内部部分更改为此:
SELECT city_id, type, x, y, 'cities_buildings' AS table_name FROM cities_buildings
UNION ALL
SELECT city_id, type, x, y, 'map_buildings' AS table_name FROM map_buildings
If you follow this approach using UNION
(without ALL
) would be pointless since there will be no common rows between the tables. 如果您采用这种方法,那么使用UNION
(不带ALL
)将毫无意义,因为表之间将没有公共行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.