MySQL-加入a或b [英] MySQL - JOIN a OR b
问题描述
假设我有一个TABLE a
,其中COLUMN data
是要加入的另外两个表(TABLE b
和TABLE c
)的一个,因为我想获得一个<b
或c
中的c4>.
问题是a.data
将与b.data
仅匹配仅,或与c.data
匹配仅.
Let's say I have a TABLE a
in which a COLUMN data
is the one to join on for 2 other tables (TABLE b
and TABLE c
) because I want to get a COLUMN info
in b
or c
.
The thing is a.data
will match only with b.data
or only with c.data
.
- 如何基于
a
获取b.info
或c.info
?
- How can I get
b.info
orc.info
based ona
?
经过多次尝试使用明显错误的语法后,我做的最好的就是两个查询:
After many attempts with obviously wrong syntax, the best I did was in 2 queries:
SELECT b.info FROM a INNER JOIN b ON a.data = b.data
SELECT c.info FROM a INNER JOIN c ON a.data = c.data
我想实现一些看起来像这样的东西:
I would like to achieve something that could look like this:
SELECT alias.info FROM a INNER JOIN (b OR c) AS alias ON a.data = alias.data
实际上,我可以获取所需的数据并使用PHP进行处理.但是我正在做一个巨大的过程(与我的问题无关),而不是一个好的查询,并且页面需要太多时间来加载.
Actually I can get the data I want and work with it using PHP. But I am making a huge process (unrelated to my question) instead of a good query and the page takes too much time to load.
推荐答案
您可以保留对b
和c
表的联接,然后使用不是NULL
的info
字段:
You can left join to both of the b
and c
tables, then use whichever info
field is not NULL
:
select coalesce(b.info, c.info) info
from a
left join b on a.data = b.data
left join c on a.data = c.data
这篇关于MySQL-加入a或b的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!