How to use LIKE statement with multiple values from another field?

寵の児 提交于 2020-01-16 00:35:29

问题


I want to select all records where field contains values from another field. How do I do that? Here is a code that I am trying.

select field1 , field2, field3 
from table1
where field1 like '%'+(select distinct field4 from table2)+'%'


Thanks in advance.


回答1:


Just do your like as a join condition:

select field1 , field2, field3 
from table1
join (select distinct field4 from table2) x
  on field1 like '%'+field4+'%'



回答2:


Using the original structure of your query, you can do:

select field1, field2, field3 
from table1 t1
where exists (select 1
              from table2
              where t1.field1 like '%' + field4 + '%'
             );

The advantage of this method is that it will not duplicate records in table1. For instance, if there are two rows in table2 with the values 'a' and 'b' respectively and one row in table1 with the value 'ab', then this method will only return the row from table1 once.



来源:https://stackoverflow.com/questions/29181640/how-to-use-like-statement-with-multiple-values-from-another-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!