繁体   English   中英

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

[英]Query SQL with like operator from two tables

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

我需要这样的东西:

select * from table1 where name like %table2.name

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

编辑

(原来的答案是进一步下来)

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

为此,您可以将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在表b找到bar =“ne”,然后预先设置%运算符并使用它来过滤a结果。 结果是:

one
tone
phone

如果您可以将运算符存储在b.bar ,则无需执行concat。

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

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'

这将从someTable foo ,从someOtherTablesomeTable bar ,其中行与someField相关, foo以“SOMETHING”开头, bar以“SOMETHING ELSE”结束。

对确切的语法不是特别肯定,但这里有一个想法:

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

基于@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM