如何使用like
来自两个不同表的运算符进行 SQL 查询?
我需要类似的东西:
select * from table1 where name like %table2.name
它不是公共字段,而是另一个表上字段的子字符串。
如何使用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
s,然后...LIKE concat('%', b.bar)
改用。)
它使用id
= 2 在 table 中查找bar
= "ne" b
,然后%
添加运算符并使用它来过滤来自a
. 结果是:
one
tone
phone
如果您可以将运算符存储在b.bar
.
另外,我惊讶地发现这也适用(在 SQL Server 上):
SELECT foo
FROM a
WHERE foo LIKE (
SELECT TOP 1 '%' + bar
FROM b
WHERE id = 2
)
...但使用的版本JOIN
可能更灵活。
那应该让你继续前进。
(可以说不再相关)
很难说出你在问什么,但这里有一个使用LIKE
来限制 a 的结果的例子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'
这将为您foo
提供someTable
与行相关的位置bar
和位置,并以“SOMETHING”开头并以“SOMETHING ELSE”结尾。someOtherTable
someField
foo
bar
不太确定确切的语法,但这里有一个想法:
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