在下表中..我应该检索删除为false且禁用的所有行为true且不同的短语..如果短语不是表中唯一的一个(例如“bad”)单词)..我必须使用device_id返回一个..如果它只是表中的一个,即使device_id为空,我也必须返回它。
id | device_id | phrase | disabled | deleted |
----+-----------+---------+----------+---------+
2 | 1 | WTF | f | f |
3 | 1 | White | f | f |
4 | | WTF | f | f |
5 | | wTf | f | f |
6 | 2 | fck | f | f |
7 | 1 | damn | f | f |
8 | 1 | bitch | f | f |
9 | 1 | crap | f | f |
1 | 1 | Shit | t | t |
10 | 1 | ass | f | f |
11 | | bad | f | f |
12 | 1 | bad | t | f |
13 | 1 | badshit | f | f |
我所做的就是这个查询并返回我所期望的...(例如,返回只有1个“坏”字,而device_id = 1)
select distinct on (phrase) id, device_id, phrase, disabled, deleted
from filter
where phrase like '%' and deleted = false and
(device_id is null or device_id = 1)
order by phrase;
但是当添加关键字搜索时,例如“坏”..
select distinct on (phrase) id, device_id, phrase, disabled, deleted
from filter
where phrase like '%bad%' and deleted = false and
(device_id is null or device_id = 1)
order by phrase;
返回是“badshit”(ok)和“bad”(但是device_id为null)..我的预期是“坏”字的device_id是1 ..
我是postgresql的新手..谢谢!
答案 0 :(得分:1)
9个月前,我已经修复了此错误,但由于忙于将其发布在这里。
这是我的答案:
order by phrase, device_id
答案 1 :(得分:0)
或者:
select distinct on (phrase) id, device_id, phrase, disabled, deleted
from filter
where phrase like '%bad%' and deleted = false and
(device_id is not null)
order by phrase;
或:
select distinct on (phrase) id, device_id, phrase, disabled, deleted
from filter
where phrase = 'bad' and deleted = false and
(device_id is null or device_id = 1)
order by phrase;
首先,如果您只想检索设备中没有空值的记录。第二,如果你想检索精确短语的记录。
where phrase like '%bad%'
特别要求postgres返回坏的和坏的****,因为他们都是'喜欢'坏。
另一方面,在寻求帮助之前清理你的帖子。
答案 2 :(得分:0)
没关系,我通过添加device_id来修复它:
order by phrase;
到
order by phrase, device_id;
答案 3 :(得分:0)
DISTINCT ON(expression [,...])仅保留给定表达式求值相等的每组行的第一行。使用与ORDER BY相同的规则来解释DISTINCT ON表达式(请参见上文)。请注意,除非使用ORDER BY来确保所需的行首先出现,否则每个集合的“第一行”都是不可预测的。例如:
url=`cat desired_url`
wget "$url"
检索每个位置的最新天气报告。但是,如果我们没有使用ORDER BY强制每个位置的时间值从高到低排序,那么我们将从每个位置的不可预测的时间获得报告。
DISTINCT ON表达式必须与最左边的ORDER BY表达式匹配。 ORDER BY子句通常会包含其他表达式,这些表达式确定每个DISTINCT ON组中所需的行优先级
对于您的情况,请根据需要使用以下代码device_id = 1
SELECT DISTINCT ON (location) location, time, report
FROM weather_reports
ORDER BY location, time DESC;