简体   繁体   中英

SELECT FROM two different tables with the same WHERE clause?

I have two different tables. cities_buildings and 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.

If you have duplicates in the tables and don't want duplicates in the output, use UNION instead of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM