【问题标题】:Mysql Left Join Condition on column value starts with列值上的Mysql左连接条件以
【发布时间】:2019-08-08 17:51:54
【问题描述】:

我正在尝试左连接两个不同的表,具体取决于 Type 列中的值以哪个字符开头。

例如:
如果type列的值以's'开头=>左连接表a
如果type列的值以'g'开头 => Left Join table b

如何创建这种条件?

【问题讨论】:

  • 我想不出你为什么要在一个结构良好的数据库上做这个!?!
  • 不幸的是,这是一个已有 15 年历史的数据库,结构不完善,我需要添加一些查询。

标签: mysql conditional left-join


【解决方案1】:

您可以通过在 ON 子句中应用条件来尝试以下操作

select * from tablename x
left join tableA y on x.id=y.id and x.type like 's%'
left join tableB z on x.id=z.id and x.type like 'g%'

【讨论】:

    【解决方案2】:

    您可以使用以下解决方案:

    SELECT *
    FROM table_name t 
        LEFT JOIN A ON LEFT(t.type, 1) = 's' AND t.id = A.tid
        LEFT JOIN B ON LEFT(t.type, 1) = 'g' AND t.id = B.tid
    

    demo on dbfiddle.uk

    【讨论】:

      猜你喜欢
      • 2016-03-17
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 2020-11-07
      • 2015-10-28
      • 2016-03-10
      相关资源
      最近更新 更多