我要运行此查询:
SELECT DISTINCT ON (address_id) purchases.address_id, purchases.* FROM purchases WHERE purchases.product_id = 1 ORDER BY purchases.purchased_at DESC
但是我得到这个错误:
PG ::错误:错误:SELECT DISTINCT ON表达式必须匹配初始ORDER BY表达式
添加address_id为第一个ORDER BY表达式可使错误静音,但我真的不想添加sorting over address_id。是否可以不按顺序进行address_id?
address_id
ORDER BY
文档说:
DISTINCT ON(expression [,…])仅保留给定表达式求值相等的每组行的第一行。[…]注意,除非使用ORDER BY来确保所需的行首先出现,否则每个集合的“第一行”都是不可预测的。[…] DISTINCT ON表达式必须与最左边的ORDER BY表达式匹配。
官方文件
因此,您必须将“”添加address_id到订单依据。
另外,如果您要查找包含每个产品最近购买的产品address_id并按结果排序的整行,purchased_at那么您正在尝试解决最大的每组N个问题,可以通过以下方法解决:
purchased_at
适用于大多数DBMS的常规解决方案:
SELECT t1.* FROM purchases t1 JOIN ( SELECT address_id, max(purchased_at) max_purchased_at FROM purchases WHERE product_id = 1 GROUP BY address_id ) t2 ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at ORDER BY t1.purchased_at DESC
基于@hkf的答案的更面向PostgreSQL的解决方案:
SELECT * FROM ( SELECT DISTINCT ON (address_id) * FROM purchases WHERE product_id = 1 ORDER BY address_id, purchased_at DESC ) t ORDER BY purchased_at DESC