【问题标题】:MySQL - Join table on column A unless column A = x then join on column b insteadMySQL - 在列 A 上加入表,除非列 A = x 然后加入列 b
【发布时间】:2017-03-30 11:37:31
【问题描述】:

如果第一列等于特定值,是否可以在不同列上加入表。

见下文:

表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

【问题讨论】:

  • 能否请您添加所需的输出也有问题?到时候帮到你就很容易了。
  • x 可以为空吗??
  • ON (tableA.ID = tableB.id1 AND tableB.id1 <> x) OR (tableA.ID = tableB.id2)

标签: mysql sql join


【解决方案1】:

您可以在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)

【讨论】:

  • 如果 x 为空怎么办?
  • x是否为null没关系...只会影响运营商...逻辑是一样的...
  • 非常感谢!工作了一个款待:-D
猜你喜欢
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多