20

您将如何使用“LIKE”在子查询中进行搜索?

例如,我尝试过这样做,但不起作用:

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%' AND t1.surname LIKE ' %t2.surname%'

我该怎么做?

4

7 回答 7

29

使用连接:

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

myothertable...但是如果给定mytable记录有多个匹配项,则可能存在重复项。

使用存在:

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

使用全文搜索MATCH(需要myothertableMyISAM)

SELECT a.*
  FROM mytable a
  JOIN myothertable b ON MATCH(a.name) AGAINST (b.name)
于 2012-04-05T03:46:13.783 回答
12

例如:

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

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

于 2012-04-05T03:38:40.117 回答
2

只是另一种方式:

select a.field, b.code
from table1 a 
inner join (select code from table2 where ....) b on a.field like CONCAT('%', b.code, '%')
于 2014-09-05T07:55:47.793 回答
2

这个字符串对我来说很好。

"SELECT * FROM table1 WHERE field like CONCAT('%', (SELECT id FROM table2), '%')";
于 2016-07-08T12:38:31.810 回答
0

它对我有用

SELECT *
FROM mytable
WHERE name
LIKE CONCAT('%',(SELECT name FROM myothertable),'%')
于 2013-02-15T11:28:37.233 回答
0
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))
于 2013-08-16T01:51:15.523 回答
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
于 2012-04-05T04:45:17.673 回答