这是我的查询。基本上,我想使用@Remote.ImportantVal
:
LEFT JOIN
declare @Local table
(
LocalId varchar(15),
Match1 int,
Match2 varchar(5)
)
insert into @local select '12_012_112', 5, 'MATH'
insert into @local select '12_012_113', 5, 'MATH'
insert into @local select '12_012_114', 5, 'MATH'
declare @Remote table
(
RemoteId varchar(15),
ImportantVal varchar(20),
Match1 int,
Match2 varchar(5)
)
insert into @Remote select 'ABC0012_012_112', 'Important', 5, 'MATH'
insert into @Remote select 'ABC0112_012_113', 'Important', 5, 'MATH'
insert into @Remote select 'ABC0012_012_114', 'Important', 5, 'MATH'
select l.localId, r.RemoteId, r.ImportantVal
from @Local l left join @Remote r on 'ABC%' + l.LocalId like r.RemoteId
and l.Match1 = r.Match1
and r.Match2 = r.Match2
似乎问题是%
,但它是必需的,因为 ABC 之后的2个字符将永远不会相同。在上一个查询中,两个表不匹配,它返回3个空行。
如果我使用这样的东西,那么只有2行匹配,因为它基本上是inner join
:
select l.localId, r.RemoteId, r.ImportantVal
from @Local l left join @Remote r on 'ABC00' + l.LocalId like r.RemoteId
and l.Match1 = r.Match1
and r.Match2 = r.Match2
我还尝试使用left join
子句where
,但只是将其转换为inner join
,因此不会返回任何内容:
select l.localId, r.RemoteId, r.ImportantVal
from @Local l left join @Remote r on 'ABC%' + l.LocalId like r.RemoteId
where l.Match1 = r.Match1
and r.Match2 = r.Match2
使用left join
和%
,如何匹配两个表中的所有三行?
感谢。
答案 0 :(得分:3)
更改join子句中参数的顺序:
create table a (i int not null,sequence_id int not null);
insert a(i,sequence_id) values (1,1),(1,2);
select ifnull(max(sequence_id),0) as prevMax from a where i=1;
-- answer is 2
select ifnull(max(sequence_id),0) as prevMax from a where i=7;
-- answer is 0
你应该得到你期望的三行。 (至少我的测试给出了这个)。
如文档中所述,必须在类似表达式右侧的模式中使用通配符:
match_expression [NOT] LIKE模式[ESCAPE escape_character]
答案 1 :(得分:0)
您可以在WHERE
;
样本数据;
CREATE TABLE #Local (LocalId varchar(15), Match1 int, Match2 varchar(5))
INSERT INTO #Local
VALUES
('12_012_112', 5, 'MATH')
,('12_012_113', 5, 'MATH')
,('12_012_114', 5, 'MATH')
CREATE TABLE #Remote (RemoteId varchar(15), ImportantVal varchar(20), Match1 int, Match2 varchar(5))
INSERT INTO #Remote
VALUES
('ABC0012_012_112', 'Important', 5, 'MATH')
,('ABC0112_012_113', 'Important', 5, 'MATH')
,('ABC0012_012_114', 'Important', 5, 'MATH')
实际查询;
SELECT
l.LocalId
,r.RemoteId
,r.ImportantVal
FROM #Local l
LEFT JOIN #Remote r
ON r.RemoteId LIKE 'ABC%'
AND l.LocalID = RIGHT(r.RemoteId,LEN(l.LocalId))
AND l.Match1 = r.Match1
AND l.Match2 = r.Match2
答案 2 :(得分:0)
为什么不呢:
select l.localId, r.RemoteId, r.ImportantVal
from @Local l left join @Remote r on RIGHT(l.LocalId,10) = r.RemoteId
and l.Match1 = r.Match1
and r.Match2 = r.Match2
或者,如果“ABC”很重要,那么
select l.localId, r.RemoteId, r.ImportantVal
from @Local l left join @Remote r on RIGHT(l.LocalId,10) = r.RemoteId
and l.LocalId like 'ABC%'
and l.Match1 = r.Match1
and r.Match2 = r.Match2