MYSQL在'WHERE'子句中使用'LIKE'来搜索子查询

时间:2012-04-05 03:34:10

标签: mysql sql subquery where-clause sql-like

你如何使用'LIKE'来搜索子查询?

E.g。我试过这样做,但是不起作用:

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

到目前为止,我有这个:

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))

它工作正常,因为它返回完全匹配,但它似乎没有返回我的其他类似的记录,所以我还要检查:

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

我该怎么做?

7 个答案:

答案 0 :(得分:23)

使用JOIN:

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

...但如果给定myothertable条记录mytable中有多个匹配项,则可能会有重复项。

使用EXISTS:

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

使用Full Text Search MATCH(需要myothertable是MyISAM)

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

答案 1 :(得分:11)

例如:

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

就术语而言:这被称为相关子查询。

答案 2 :(得分:2)

另一种方式:

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

答案 3 :(得分:0)

最好的方法是创建名为NameMatch()的函数

最终查询:

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

该功能如下:

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

答案 4 :(得分:0)

它为我工作

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

答案 5 :(得分:0)

SELECT * FROM t1 WHERE11.name IN(SELECT t2.name FROM t2) AND(t1.title IN(SELECT t2.title FROM t2)     或者t1.surname IN(SELECT t2.surname FROM t2))

答案 6 :(得分:0)

这个字符串适用于我。

" SELECT * FROM table1 WHERE字段,如CONCAT('%',(SELECT id FROM table2),'%')&#34 ;;