MySQL-加入a或b [英] MySQL - JOIN a OR b

查看:90
本文介绍了MySQL-加入a或b的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个TABLE a,其中COLUMN data是要加入的另外两个表(TABLE bTABLE c)的一个,因为我想获得一个<bc中的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.infoc.info?
  • How can I get b.info or c.info based on a ?


经过多次尝试使用明显错误的语法后,我做的最好的就是两个查询:

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.

推荐答案

您可以保留对bc表的联接,然后使用不是NULLinfo字段:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆