使用来自两个表的like运算符查询SQL

时间:2010-01-21 09:12:22

标签: sql sql-server sql-like

如何使用来自两个不同表的like运算符进行SQL查询?

我需要类似的东西:

select * from table1 where name like %table2.name

它不是常见字段,而是另一个表上字段的子字符串。

3 个答案:

答案 0 :(得分:4)

修改

(原始答案进一步下调)

您的评论(以及后续编辑)完全改变了问题。

为此,您可以将LIKE用作联接中ON子句的一部分:

CREATE TABLE a (foo varchar(254))
GO

CREATE TABLE b (id int, bar varchar(254))
GO

INSERT INTO a (foo) VALUES ('one')
INSERT INTO a (foo) VALUES ('tone')
INSERT INTO a (foo) VALUES ('phone')
INSERT INTO a (foo) VALUES ('two')
INSERT INTO a (foo) VALUES ('three')

INSERT INTO b (id, bar) VALUES (2, 'ne')
INSERT INTO b (id, bar) VALUES (3, 't')

SELECT a.foo
FROM a
INNER JOIN b ON a.foo LIKE '%' + b.bar
WHERE b.id = 2

(这是SQL Server版本;对于MySQL,添加各种分号,删除GO,然后使用...LIKE concat('%', b.bar)。)

使用id = 2查找表bar中的b =“ne”,然后预先设置%运算符并使用它来过滤{{1}的结果}}。结果是:

a

如果您可以将操作员存储在one tone phone

,则无需执行连接

另外,我很惊讶地发现这也适用于(在SQL Server上):

b.bar

...但使用SELECT foo FROM a WHERE foo LIKE ( SELECT TOP 1 '%' + bar FROM b WHERE id = 2 ) 的版本可能更灵活。

这应该让你去。

原始答案

(可以说不再相关)

很难说出你在问什么,但这里有一个使用JOIN来限制LIKE的结果的例子:

JOIN

这将从SELECT a.foo, b.bar FROM someTable a INNER JOIN someOtherTable b ON a.someField = b.someField WHERE a.foo LIKE 'SOMETHING%' AND b.bar LIKE '%SOMETHING ELSE' foosomeTable bar someOtherTable给您someField,其中行与foo相关,bar以“{1}}开头SOMETHING“和{{1}}以”SOMETHING ELSE“结束。

答案 1 :(得分:3)

对于确切的语法并不是特别确定,但这是一个想法:

select ... from (
    select ID, Foo as F from FooTable
    union all
    select ID, Bar as F from BarTable) R
where R.F like '%text%'

答案 2 :(得分:1)

基于@TJCrowder回答

测试表

create table #A (
id varchar(10)
)


create table #b(
number varchar(5)
)

insert into #A values('123')
insert into #A values('456')
insert into #A values('789')
insert into #A values('0123')
insert into #A values('4567')

select * from #A

insert into #B values('12')
insert into #b values('45')
insert into #b values('987')
insert into #b values('012')
insert into #b values('666')

实际查询

select * from #a, #b
where #a.id like '%' + #b.number + '%'

根据需要修改上述查询,例如

select #A.* from #A,#B ...
or
select * from #a, #b
where #a.id like  #b.number + '%'  -- one side match