【问题标题】:How to find for the list of code from another table using like function (Oracle sql )?如何使用类似函数(Oracle sql)从另一个表中查找代码列表?
【发布时间】:2020-06-04 07:53:04
【问题描述】:

我有一个表调用“student_table”表,它有超过 100 个 STD_ID, 我需要从“Reg_table”表中映射 Student_reg_ID

student_table 格式

STD_ID
123
456
789
688

Reg_table 格式 第 1 列:Student_reg_ID 第 2 栏:参考

Student_reg_ID    Reference
23124             stden id 123
56142             customer refer 456
14328             refer -  789
67890             code ref : 688

需要输出

STD_ID    Student_reg_ID 
123       23124
456       56142
789       14328
688       14328

我怎样才能得到如上图所示的输出?

不想想在下面的类似函数中给出 100 多个 STD_ID

STD_ID Like  '%123% or '%456% or .......

如何在单个 sql 中获取它?

【问题讨论】:

  • 看起来你想要reference like '% ' || std_id'

标签: sql oracle sql-like


【解决方案1】:

您在这里使用LIKE 是正确的。试试这个选项:

SELECT
    st.STD_ID,
    rt.Student_reg_ID
FROM student_table st
LEFT JOIN Reg_table rt
    ON rt.Reference LIKE '%' || st.STD_ID || '%';

请注意,如果 STD_ID 列是一个数字,那么在进行 LIKE 比较之前,您首先必须转换为文本,即使用此:

LEFT JOIN Reg_table rt
    ON rt.Reference LIKE '%' || TO_CHAR(st.STD_ID) || '%';

编辑:

考虑到STD_ID 的值可能并不总是三位数,我们可以在加入时使用REGEXP_LIKE 强制完全匹配:

SELECT
    st.STD_ID,
    rt.Student_reg_ID
FROM student_table st
LEFT JOIN Reg_table rt
    ON REGEXP_LIKE(rt.Reference, '(^|\s)' || st.STD_ID || '(\s|$)');

【讨论】:

  • 你也可以将我的演示复制到你的答案中,因为它们是相同的......然后我会删除我的。
  • @Nick Nah...不要删除,让它酝酿,最终它会得到投票。
  • 这只有在所有 STD_ID 都是三位数长的情况下才有效。否则你会得到误报,例如ID 1、2、3、12、23 和 123 都匹配“stden id 123”。根据样本数据,lousia 比较想要rt.reference like '% ' || st.std_id'
  • 我认为没有理由怀疑这种极端情况。
  • @ThorstenKettner 我同意你的观点,如果 ID 不总是三位数,我提供了一个替代答案。
猜你喜欢
  • 1970-01-01
  • 2020-06-14
  • 2021-09-17
  • 2019-07-09
  • 1970-01-01
  • 2013-12-14
  • 2015-01-29
  • 2020-10-22
相关资源
最近更新 更多