如果第一列等于特定值,是否可以在不同列上连接表。
见下文:
表A
.----+-----------------.
| ID | Name |
+----+-----------------+
| 1 | Name goes here1 |
| 2 | Name goes here2 |
| 3 | Name goes here3 |
| 4 | Name goes here4 |
.----+-----------------+
表B
.----+-----------------+-----------------.
| ID | id1 | id2 |
+----+-----------------+-----------------+
| 1 | ID goes here | ID goes here |
| 2 | ID goes here | ID goes here |
| 3 | ID goes here | ID goes here |
| 4 | ID goes here | ID goes here |
.----+-----------------+-----------------.
例如,我想加入 tableA ON tableA.ID = tableB.id1 UNLESS tableB.id1 = x THEN JOIN ON tableB.id2
最佳答案
您可以将其表达为 on
子句中的基本逻辑:
on (a.id = b.id1 and b.id1 <> x) or
(a.id = b.id2 and b.id1 = x)
如果x
可以是NULL
,逻辑会稍微复杂一些,但你绝对可以使用相同的想法。如果想法是测试 NULL
,那么表达查询的更简单方法是:
on a.id = coalesce(b.id1, b.id2)
关于MySQL - 在 A 列上联接表,除非 A 列 = x,然后在 b 列上联接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43116798/