MYSQL use 'LIKE' in 'WHERE' clause to search in subquery

笑着哭i 提交于 2019-12-21 07:24:20

问题


How would you use 'LIKE' to search in a subquery?

E.g. i've tried doing this, but doesn't work:

SELECT *
FROM mytable
WHERE name
    LIKE '%
        (SELECT name FROM myothertable)
        %'

I have this so far:

SELECT * FROM t1
WHERE t1.name IN (SELECT t2.name FROM t2)
AND (t1.title IN (SELECT t2.title FROM t2)
    OR t1.surname IN (SELECT t2.surname FROM t2))

It's working ok as it returns exact matchs, but it doesn't seem to return my other records that are similar, so I would like to also check that:

t1.title LIKE '%t2.title%' AND t1.surname LIKE '%t2.surname%'

How would i do this?


回答1:


Using a JOIN:

SELECT a.*
  FROM mytable a
  JOIN myothertable b ON a.name LIKE CONCAT('%', b.name, '%')

...but there could be duplicates, if there's more than one match in myothertable for a given mytable record.

Using EXISTS:

SELECT a.*
  FROM mytable a
 WHERE EXISTS (SELECT NULL 
                 FROM myothertable b 
                WHERE a.name LIKE CONCAT('%', b.name, '%'))

Using Full Text Search MATCH (requires myothertable is MyISAM)

SELECT a.*
  FROM mytable a
  JOIN myothertable b ON MATCH(a.name) AGAINST (b.name)



回答2:


For example:

SELECT a_column
FROM   mytable t
WHERE  EXISTS (
           SELECT 1
           FROM   myothertable ot
           WHERE  t.`name` LIKE '%' || ot.`name` || '%');

As far as terminology goes: this is known as a correlated subquery.




回答3:


Just another way:

select a.field, b.code
from table1 a 
inner join (select code from table2 where ....) b on a.field like CONCAT('%', b.code, '%')



回答4:


Best way would be to create function called NameMatch()

Final Query :

SELECT * FROM mytable  WHERE dbo.NameMatch(name) = 1  

The function would look like :

create function dbo.NameMatch 
(@_name varchar(100))
returns bit 
as  begin

    declare @res bit 
    if exists (select 1 from myothertable where @_name like '%' + name + '%' )
     set @res = 1
    else set @res  = 0
    return @res

end



回答5:


It Worked FOR ME

SELECT *
FROM mytable
WHERE name
LIKE CONCAT('%',(SELECT name FROM myothertable),'%')



回答6:


SELECT * FROM t1 WHERE t1.name IN (SELECT t2.name FROM t2) AND (t1.title IN (SELECT t2.title FROM t2) OR t1.surname IN (SELECT t2.surname FROM t2))




回答7:


this string works fine for me.

"SELECT * FROM table1 WHERE field like CONCAT('%', (SELECT id FROM table2), '%')";



来源:https://stackoverflow.com/questions/10022338/mysql-use-like-in-where-clause-to-search-in-subquery

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