【问题标题】:sql join with like operator使用like运算符进行sql连接
【发布时间】:2020-04-29 22:59:58
【问题描述】:

嗨,我的 sqltable 中有 2 个表,其中我的第一个表的 id 为 111,112,113 等,第二个表具有相同的列也有列 id,其中包含 111|aa,112|ab,114|ad 等值,我需要从第二个表中选择包含第一列的部分 id 的所有 id,例如第二个表包含 111 和 112,它们也在 table1 中作为 111 和 112 我如何选择那些在查询下尝试但没有得到结果的记录。

    select t1.id,t2.id from table1 t1 left outer join table2 t2 where t2.id like t2.id +'%'
    also tried.
    select t1.id,t2.id from table1 t1 left outer join table2 t2 on t2.id like t2.id +'%'

谁能给我一个提示我应该怎么做。

【问题讨论】:

  • 我删除了不兼容的数据库标签。请仅使用您真正使用的数据库进行标记。

标签: sql


【解决方案1】:

您必须使用CONCAT 来添加% 字符:

SELECT t1.id,t2.id 
FROM table1 t1 LEFT JOIN table2 t2 ON t2.id LIKE CONCAT(t1.id, '|%')

demo on dbfiddle.uk

注意:还要确保您在ON 子句中使用了正确的列。在上面的演示和查询中t1.id是数字列(包含111112113),t2.id是字符串列(包含111|aa112|ab114|ad)。

为避免大于 999 的数字出现意外行为,您也可以在条件中添加管道字符 |

【讨论】:

    【解决方案2】:

    您可以尝试使用正确的 ON 子句

    select t1.id,t2.id 
    from table1 t1 
    left outer join table2 t2 ON  t1.id like concat(t2.id, '%')
    

    select t1.id,t2.id 
    from table1 t1 
    left outer join table2 t2 ON  t2.id like concat(t1.id, '%')
    

    对于联接,您应该使用两个表中的列而不是同一个表中的列

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多