2016-03-01 23 views
0

我正在寫一個包含循環引用的表的遞歸sql。 沒問題!我讀到,你可以建立一條獨特的路徑來防止無限循環。現在我需要將列表過濾到鏈中的最後一條記錄。但我一定在做錯事。 - 編輯我將更多記錄添加到此示例中,以便更清楚爲什麼只選擇最長的記錄不起作用。獲取行的值不是另一行中的子字符串

這是一個示例表:

create table strings (id int, string varchar(200)); 
insert into strings values (1, '1'); 
insert into strings values (2, '1,2'); 
insert into strings values (3, '1,2,3'); 
insert into strings values (4, '1,2,3,4'); 
insert into strings values (5, '5'); 

而且我的查詢:

select * from strings str1 where not exists 
(
    select * from strings str2 
    where str2.id <> str1.id 
    and str1.string || '%' like str2.string 
) 

我期望只得到了最後一個記錄

| id | string | 
|----|---------| 
| 4 | 1,2,3,4 | 
| 5 |  5 | 

相反,我把他們都弄到

| id | string | 
|----|---------| 
| 1 |  1 | 
| 2 |  1,2 | 
| 3 | 1,2,3 | 
| 4 | 1,2,3,4 | 
| 5 |  5 | 

鏈接到SQL小提琴:http://sqlfiddle.com/#!15/7a974/1

回答

0

我的問題是圍繞'喜歡'的比較。

select * from strings str1 
where not exists 
(
    select 
     * 
    from 
     strings str2 
    where 
     str2.id <> str1.id 
     and str2.string like str1.string || '%' 
) 
相關問題