在两个表之间如何选择一个特定值的id所在的表存在mysql [英] Between two tables how does one SELECT the table where the id of a specific value exists mysql
问题描述
在我的Hiking数据库中有两个表,我们称表1被称为Forest,表2被称为Mountain。两个表在表Trip中都有一个 FOREIGN KEY
Trip_id,它是一个 PRIMARY KEY
是一个组成的例子)是 AUTO_INCREMENT
。
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.
我想要 SELECT * FROM $ c的行程可以是Mountain或Forest,因此这两个表不共享任何Trip_ids。 $ c>取决于哪一个具有某个值的
Trip_id
(让我们说74)的森林或山。
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).
推荐答案
假设它们有相同的列,那么使用 union all
:
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;
这篇关于在两个表之间如何选择一个特定值的id所在的表存在mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!