【问题标题】:Get rows where value is not a substring in another row获取值不是另一行中的子字符串的行
【发布时间】:2016-03-01 17:43:26
【问题描述】:

我正在针对包含循环引用的表编写递归 sql。 没问题!我读到您可以构建一条独特的路径来防止无限循环。现在我需要将列表过滤到链中的最后一条记录。不过,我一定是做错了什么。 -edit 我正在向这个示例添加更多记录,以更清楚地说明为什么只选择最长的记录不起作用。

这是一个示例表:

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 fiddle:http://sqlfiddle.com/#!15/7a974/1

【问题讨论】:

    标签: sql recursion substring


    【解决方案1】:

    我的问题在于“LIKE”比较。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      • 2013-04-22
      相关资源
      最近更新 更多