MySQL - 在 A 列上联接表,除非 A 列 = x,然后在 b 列上联接

标签 mysql sql join

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

见下文:

表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/

相关文章:

PHP错误: Call to a member function fetch_assoc() on boolean

mysql - Spring-Boot,无法使用spring-data JPA在MySql中保存unicode字符串

sql - 甲骨文 11g : Joins

ruby-on-rails - 需要帮助理解 Rails 事件记录查询

python - 连接数据帧的片段

sql - 活跃用户 SQL 查询

mysql - 多值M建模的方法有哪些 : N relationship?

sql - 需要有关 sql 查询的帮助

sql - 从 postgresql DB 中的 jsonb 列检索数据作为数组,返回空结果

sql - 在更新语句上使用输出子句时出现奇怪的错误?