简体   繁体   中英

Between two tables how does one SELECT the table where the id of a specific value exists mysql

I have 2 tables in my "Hiking" database lets say table 1 is called "Forest" and table 2 is called "Mountain". Both tables have a FOREIGN KEY "Trip_id" which is a PRIMARY KEY in table "Trip" (or something, this is a made up example) that is AUTO_INCREMENT . A trip can either be Mountain or Forest, so the 2 tables do not share any Trip_ids.

I want to SELECT * FROM either Forest or Mountain depending on which one has the Trip_id of a certain value (lets say 74).

SELECT * FROM FOREST OR MOUNTAIN WHERE Trip_id = 74 EXISTS; 

(I know this code is rubbish and completely wrong but I hope it helps illustrate what I am aiming for).

Assuming they have the same columns, then use union all :

select m.*
from mountains m
where m.trip_id = 74
union all
select f.*
from forests f
where f.trip_id = 74;
SELECT Forest.Trip_id, Hikes.Trip_id
FROM Forest, Hikes  
WHERE  Forest.Trip_id OR Hikes.Trip_id = 74;  

http://sqlfiddle.com/#!9/f8c9e7/1

Your best bet is to have all of your locations (or whatever the case is in the actual DB) in one table with a type code. If they are heterogeneous objects then you can use a pattern where you have a single shared table with individual tables for each type that have a 1:1 relationship. For example, Destinations (with data that is shared between mountains and forests), with a destination_id in the Hikes table and then tables for Mountains (with data that is specific to mountains) and Forests , each of which has a destination_id that is also its primary key.

Barring that, you can do something like this:

SELECT
    H.name,
    CASE
        WHEN M.mountain_id IS NOT NULL THEN M.name
        WHEN F.forest_id IS NOT NULL THEN F.name
        ELSE NULL
    END AS destination_name
FROM
    Hikes H
LEFT OUTER JOIN Mountains M ON M.mountain_id = H.destination_id
LEFT OUTER JOIN Forests F ON F.forest_id = H.destination_id
WHERE
    H.destination_id = 74

You'll continue to run into problems with that structure though, in my experience.

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