【问题标题】:PostgreSQL filter table with LIKE on another tablePostgreSQL 在另一个表上使用 LIKE 过滤表
【发布时间】:2020-10-13 07:00:34
【问题描述】:

我有两张桌子:

维基百科:

Id, Title
1,USA
2,USA Army
3,Canada
4,Britain

事件:

Id, Key1, Key2, Key3
1, US, USA, United States
2, Britain, Britain, Brit
3, US, US, US
4, Mex, Mexico, MX

我想从 Wikipedia 表中查找与三个关键字 Key1、Key2 或 Key3 中的任何一个匹配的所有标题条目

基本上,在前端,用户将选择一个国家,据此我计划过滤表事件。 events 表中的键列可能不一定包含国家/地区名称,它可能是与该国家/地区相关的其他内容,例如纽约

因此我现在有 3 个关键字,美国、美国、纽约,我想从这些过滤后的关键字中找到 Wikipedia 中的所有相关标题

有没有办法在没有连接的情况下过滤另一个表中的数据?

查询意图 [国家和时期的用户输入],但它对 {0} 中的任何国家/地区给出相同的结果(在“a_horse_with_no_name”的帮助下)

select title, count 
from wiki w 
where exists ( select * 
        from eventsxgeog exg 
        where actor1name = '{0}' or actor1geo_fullname = '{0}' 
        or actor2name = '{0}' or actor2geo_fullname= '{0}'
        or actiongeo_fullname= '{0}' and extract(year from dateadded) = {1} 
        and w.title in (exg.actor1name, exg.actor2name, exg.actor1geo_fullname, 
                    exg.actor2geo_fullname, exg.actiongeo_fullname)) 
and year = {1} order by count desc limit 5;

【问题讨论】:

  • 您可以执行 EXISTS,但 join 有什么问题?
  • 您认为“USA Army”与事件 1 匹配。可能是因为它以“US”和“USA”开头。因此,您的规则是标题必须以键开头吗?或者它必须包含密钥?请告诉我们您想在此处应用的确切规则。请注意,“DE”是德国的国家代码,但“DENMARK”以“DE”开头。
  • 嗨,Thorsten,我正在寻找任何类型的匹配,而不仅仅是开始。 Jarlh,我正在避免加入,因为我正在处理 3 TB 大小的数据,所以加入会减慢我的速度
  • 连接本身并不慢,但是如果有多个事件,你会得到多倍的维基百科行,这会更慢。使用 jarlh 和 a_horse_with_no_name 建议的存在子句。你知道 LIKE 条件怎么写吗?
  • 我知道如何写 LIKE,但不幸的是我无法让它工作,我收到任何用户输入的相同结果

标签: sql postgresql


【解决方案1】:

您可以使用 EXISTS 条件:

select wp.*
from wikipedia_table wp
where exists (select * 
              from events e
              where wp.title in (e.key1, e.key2, e.key3));

如果想要部分匹配,可以使用 LIKE 条件:

select wp.*
from wikipedia_table wp
where exists (select * 
              from events e
              where wp.title ilike '%'||e.key1||'%'
                 or wp.title ilike '%'||e.key2||'%'
                 or wp.title ilike '%'||e.key3||'%');

或者使用ilike any (..)更紧凑:

select wp.*
from wikipedia_table wp
where exists (select * 
              from events e
              where wp.title ilike any (array['%'||e.key1||'%', '%'||e.key2||'%', '%'||e.key3||'%'));

【讨论】:

  • 嗨!感谢您的更新,我必须更新我的问题以清楚地表达我的意图,您能重新看一下吗?
  • 奇怪的是,我对任何用户输入都有相同的结果,不知道为什么!
猜你喜欢
  • 2021-08-17
  • 2014-08-23
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多