【发布时间】:2017-08-08 17:02:55
【问题描述】:
我从 users 表中返回了一个唯一的 id 列表,相关表 (positions) 中的 where 特定列包含匹配的字符串。
每个用户记录的相关表可能有多个记录。
查询花费了非常长的时间(它不可扩展),所以我想知道我是否以某种基本方式构造了错误的查询?
用户表:
id | name
-----------
1 | frank
2 | kim
3 | jane
职位表:
id | user_id | title | company | description
--------------------------------------------------
1 | 1 | manager | apple | 'Managed a team of...'
2 | 1 | assistant | apple | 'Assisted the...'
3 | 2 | developer | huawei | 'Build a feature that...'
例如:如果相关的positions 记录在title、company 或description 列中包含“apple”,我想返回用户的id。
查询:
select
distinct on (users.id) users.id,
users.name,
...
from users
where (
select
string_agg(distinct users.description, ', ') ||
string_agg(distinct users.title, ', ') ||
string_agg(distinct users.company, ', ')
from positions
where positions.users_id::int = users.id
group by positions.users_id::int) like '%apple%'
更新
我喜欢将其移入join 子句的想法。但我要做的是根据以下条件过滤用户。而且我不确定如何在join 中做到这两点。
1) 在标题、公司、描述中查找关键字
or
2) 通过全文搜索在另一个表中的文档的关联字符串版本中查找关键字。
select
to_tsvector(string_agg(distinct documents.content, ', '))
from documents
where users.id = documents.user_id
group by documents.user_id) @@ to_tsquery('apple')
所以我最初认为它可能看起来像,
select
distinct on (users.id) users.id,
users.name,
...
from users
where (
(select
string_agg(distinct users.description, ', ') ||
string_agg(distinct users.title, ', ') ||
string_agg(distinct users.company, ', ')
from positions
where positions.users_id::int = users.id
group by positions.users_id::int) like '%apple%')
or
(select
to_tsvector(string_agg(distinct documents.content, ', '))
from documents
where users.id = documents.user_id
group by documents.user_id) @@ to_tsquery('apple'))
但是它真的很慢 - 我可以确认缓慢是来自第一个条件,而不是全文搜索。
【问题讨论】:
标签: postgresql group-by sql-like string-aggregation