1

I am bit in a struggle with a select query on one table but join 2 same columns together. To simplify my problem, I made a reconstruction of the situation. I got a table that looks like this:

declare @DummyTable Table 
(
    Id int, 
    MainName varchar(20), 
    SubName varchar(20), 
    sequenceNumber int
)

This table contains the next data:

insert into @DummyTable 
values ( 0, 'MainName1', 'SubName1', 1),
       ( 1, 'MainName1', 'SubName2', 2),
       ( 2, 'MainName1', 'SubName3', 3),
       ( 3, 'MainName1', 'SubName6', 4),
       ( 4, 'MainName1', 'SubName7', 5),
       ( 5, 'MainName2', 'SubName1', 1),
       ( 6, 'MainName2', 'SubName2', 2),
       ( 7, 'MainName2', 'SubName3', 3),
       ( 8, 'MainName2', 'SubName4', 4),
       ( 9, 'MainName2', 'SubName5', 5),
       (10, 'MainName2', 'SubName6', 6),
       (11, 'MainName2', 'SubName7', 7),
       (12, 'MainName3', 'SubName1', 1),
       (13, 'MainName3', 'SubName2', 2),
       (14, 'MainName3', 'SubName3', 3)

Now I try to get all the records containing the text MainName1 and on the same row I want also the records MainName2, matching by the SubName column, like this:

Id | MainName  | SubName  | s | Id | MainName  | SubName  | s -- s = SequenceNumber
--------------------------------------------------------------
 5 | MainName2 | SubName1 | 1 |  0 | MainName1 | SubName1 | 1
 6 | MainName2 | SubName2 | 2 |  1 | MainName1 | SubName2 | 2
 7 | MainName2 | SubName3 | 3 |  2 | MainName1 | SubName3 | 3
 8 | MainName2 | SubName4 | 4 | NULL | NULL    | NULL     | NULL
 9 | MainName2 | SubName5 | 5 | NULL | NULL    | NULL     | NULL
10 | MainName2 | SubName6 | 6 |  3 | MainName1 | SubName6 | 4
11 | MainName2 | SubName7 | 7 |  4 | MainName1 | SubName7 | 5

I try to manage this with the next query:

 select *
 from @DummyTable dt1
 left join @DummyTable dt2 on dt1.SubName = dt2.SubName
 where dt1.MainName like '%Name2%'
 and dt2.MainName like '%Name1%'
 order by dt1.MainName, dt1.sequenceNumber

But when I execute this query, I get the result I want but with records with the ids 8 and 9 missing. I tried to right join, or only join (without left or right) but all gives the same result, not showing records with the ids 8 and 9. I cannot figure out what I am doing wrong here and I am also wondering why I am not seeing the missing records. Could anyone help me to understand my problem and how I can fix it?

4

1 回答 1

2

试试这个查询:

select *
from @DummyTable dt1
left join @DummyTable dt2 on dt2.SubName = dt1.SubName and dt2.MainName like '%Name1%'
where dt1.MainName like '%Name2%' --and (dt2.MainName like '%Name1%')
order by dt1.MainName, dt1.sequenceNumber   

null由于您的where子句过滤掉了结果中不匹配的记录,您丢失了值dt2.MainName like '%Name1%'

编辑:我的查询并不能很好地工作,因为dt2对于缺少的值并不总是返回 null,所以我将参数移到 join 子句中,现在它按预期工作。

于 2013-07-01T10:13:18.427 回答