首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将一个表的列中的数据与另一个表的同一列中的数据进行比较

将一个表的列中的数据与另一个表的同一列中的数据进行比较
EN

Stack Overflow用户
提问于 2014-06-11 08:59:43
回答 2查看 801关注 0票数 0

我有两张桌子,分别是临时表和md桌。有一个名为uri_stem的字段,它包含一些我想从临时项目中省略的细节,而不是md中的内容。我需要做一个比较,它能够比较某些模式,如果md中有类似的模式,就从temp中删除它们。

现在,我正在使用这段代码来删除类似于我想要省略的模式的数据,但是我希望有一些方法能够比较md表中的模式,而不是对每个模式进行硬编码。希望解释得够清楚。

代码语言:javascript
运行
复制
FROM 
  spfmtr01.tbl_1c_apps_log_temp 
where 
 uri_stem not like '%.js' and 
 uri_stem not like '%.css' and 
 uri_stem not like  '%.gif' 
 and uri_stem not like '%.png' 
 and uri_stem not like '%.html' 
 and uri_stem not like '%.jpg' 
 and uri_stem not like '%.jpeg' 
 and uri_stem not like '%.ico' 
 and uri_stem not like '%.htm' 
 and uri_stem not  like '%.pdf' 
 and uri_stem not  like '%.Png' 
 and uri_stem not  like '%.PNG'
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-11 10:57:23

这个例子基于我在评论中提到的回答

SQLFiddle

样本数据:

代码语言:javascript
运行
复制
drop table if exists a, b;
create table a (testedstr varchar);
create table b (condstr varchar);

insert into a values 
   ('aa.aa.jpg'),
   ('aa.aa.bjpg'), -- no match
   ('aa.aa.jxpg'), -- no match
   ('aa.aa.jPg'), 
   ('aa.aa.aico'), -- no match
   ('aa.aa.ico'), 
   ('bb.cc.dd.icox'), -- no match
   ('bb.cc.dd.cco');  -- no match

insert into b values ('jpg'), ('ico');

解释:

  • 在表a中,我们有要测试的字符串(存储在testedstr列中)
  • 在表b中,我们有希望用作测试表达式的字符串(存储在condstr列中)

SQL:

代码语言:javascript
运行
复制
with cte as (select '\.(' || string_agg(condstr,'|') || ')$' condstr from b)

select * from a, cte where testedstr !~* condstr;

解释:

  • 在第一行中,我们将希望测试的所有模式聚合到一个字符串中;因此,我们将得到jpg|ico字符串(聚合为单行)。
  • 在第二行中,我们将测试表与测试表达式(从第一行中)交叉起来,并使用正则表达式来执行测试。
  • 末尾的正则表达式看起来像\.(jpg|ico)$

对于旧版本,您应该使用@Bohemian提供的答案。对于我的样本数据,它看起来像(调整了多个可能的点)这个(SQLFiddle )

代码语言:javascript
运行
复制
select 
  *
from 
  a
where 
  lower(reverse(split_part(reverse(testedstr),'.',1))) 
    not in (select lower(condstr) from b)

没有reverse函数(SQLFiddle):

代码语言:javascript
运行
复制
select 
  *,
  lower(split_part(testedstr,'.',length(testedstr)- length(replace(testedstr,'.','')) + 1)) as extension
from 
  a
where 
  lower(split_part(testedstr,'.',length(testedstr)- length(replace(testedstr,'.','')) + 1)) not in (select lower(condstr) from b)
票数 0
EN

Stack Overflow用户

发布于 2014-06-11 11:05:43

首先,让我们将许多条件重构为一个条件:

代码语言:javascript
运行
复制
where lower(substring(uri_stem from '[^.]+$')) not in ('js', 'css', 'gif', 'png', 'html', 'jpg', 'jpeg', 'ico', 'htm', 'pdf')

在这种形式中,很容易看出如何选择值列表而不是编码:

代码语言:javascript
运行
复制
where lower(substring(uri_stem from '[^.]+$')) not in (
    select lower(somecolumn) from sometable)

注意使用case ()来避免处理大小写变体的问题。

您还可以将其编码为一个联接:

代码语言:javascript
运行
复制
select t1.*
from mytable t1
left join sometable t2
    on lower(somecolumn) = lower(split_part(uri_stem, '.', 2))
where t2.somecolumn is null -- filter out matches
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24158699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档