【问题标题】:String pattern matching in sqlsql中的字符串模式匹配
【发布时间】:2018-05-24 14:48:57
【问题描述】:

请帮助我为以下场景编写通用 SQL 查询。 根据表 2 中的数据决定输出。对于 Eg1,如果表 2 中存在 AB*,则输出将为 AB01,AB02。 Eg2 - AB02 出现在 Table2 中,只有 AB02 在输出中 eg3 - * 出现在 Table2 中,Table1 中的所有数据都在输出中

场景 1

Table1  
AB01  
AB02  
BE01  
GH01  

Table2  
AB*

Output  
AB01  
AB02 

Scenario 2

Table1  
AB01  
AB02  
BE01  
GH01  

Table2  
AB02

Output   
AB02

场景 3

Table1

AB01  
AB02  
BE01  
GH01  

Table2  
*

Output  
AB01  
AB02  
BE01  
GH01  

【问题讨论】:

  • 这没有多大意义。似乎您正在尝试将规则存储在数据库中,以了解如何将两个表连接在一起。这尖叫着糟糕的设计,并要求您使用动态 sql。也许如果你分享一些清晰的细节,你想要什么会更明显。这是一个很好的起点。 spaghettidba.com/2015/04/24/…
  • mysql mysql @B001

标签: mysql sql pattern-matching


【解决方案1】:

在表之间的交叉连接上使用rlike

select * 
  from table1 t1, table2 t2
  where t1.col1 rlike t2.col2;

您可能需要调整 table2 中的表达式以成为标准的正则表达式模式,但这应该很容易。见https://dev.mysql.com/doc/refman/8.0/en/regexp.html

【讨论】:

    【解决方案2】:

    这应该适合你:

    select a.* from table1 a join table2 b on a.field like '%'+replace(b.field,'*','')+'%'
    

    【讨论】:

    • 在所有三种情况下都为我工作
    猜你喜欢
    • 2019-04-22
    • 2013-02-12
    • 2021-03-07
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多