SELECT FROM 具有相同 WHERE 子句的两个不同表?

SELECT FROM two different tables with the same WHERE clause?

我有两个不同的 table。 cities_buildingsmap_buildings。两者都有完全相同的 SAME COLUMN names/structure.

是否可以这样做,并且仍然保留来自 table 的每条记录?

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)

提前致谢!

你可以这样做:

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);

然而这可能更好:

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;

这与城市有关。

备选方案(最常用的是):

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);

不完全确定你想要完成什么,但也许这会做到:

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)

这会连接 table,然后从其中任何一个中找到 city_id 为 1 或 2 的行。

如果您在 table 中有重复项并且不想在输出中出现重复项,请使用 UNION 而不是 UNION ALL。不过,这会对性能产生影响。

如果您希望能够跟踪 table 行的来源,您可以将查询的内部部分更改为:

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

如果您按照此方法使用 UNION(没有 ALL)将毫无意义,因为 table 之间没有公共行。