【发布时间】:2020-12-31 18:16:32
【问题描述】:
以下尝试:
Article.objects.filter(category__id="b5e20323-8cec-413a-b405-342b3809f9a4").distinct('title').order_by("?")
给我:
ProgrammingError: SELECT DISTINCT ON 表达式必须匹配初始 ORDER BY 表达式
我尝试使用原始 SQL。所以我尝试了:
SELECT * FROM (SELECT DISTINCT title from article WHERE category_id = '...') AS inner_distinct ORDER BY RANDOM() LIMIT 3
这可行,但我需要在标题中添加一个附加字段。如果我将原始查询更改为:
SELECT * FROM (SELECT DISTINCT title, id from article WHERE category_id = '...') AS inner_distinct ORDER BY RANDOM() LIMIT 3
DISTINCT 关键字突然失效了。
我该如何克服这个问题?
编辑:假设我有一个名为 Shapes 的表。这是示例数据:
ID name
==================================== ========
2f3e9b34-0184-4e92-b205-88dac05b7cb0 Oval
b6382663-848a-4760-ad2a-3195977cf892 Line
e77a6a1a-7e99-4b00-97d3-df684e1bcc38 Line
ef7eb727-b4a8-43aa-b11f-1ddc5c0385fe Triangle
提供的解决方案(SELECT * FROM (SELECT DISTINCT ON (name) name, id from shapes AS inner_distinct ORDER BY RANDOM() LIMIT 3) 总是返回以下内容(以随机顺序)
ID name
==================================== ========
2f3e9b34-0184-4e92-b205-88dac05b7cb0 Oval
b6382663-848a-4760-ad2a-3195977cf892 Line
ef7eb727-b4a8-43aa-b11f-1ddc5c0385fe Triangle
永远不会:
e77a6a1a-7e99-4b00-97d3-df684e1bcc38 Line
代替:
b6382663-848a-4760-ad2a-3195977cf892 Line
(虽然一次一个,但有时都应该被选中!)
【问题讨论】:
-
我也会要求添加示例数据和预期结果。
标签: sql django postgresql