[英]Grab all rows columns in table apart from rows which have a non-unique value in one column
I understand that if I use something like: SELECT DISTINCT product_id FROM products;
我知道如果我使用类似的东西:
SELECT DISTINCT product_id FROM products;
It will return the product_id column with unique values.它将返回具有唯一值的 product_id 列。 However if I want to return the other columns from the table as well, is
DISTINCT
still the best approach?但是,如果我还想从表中返回其他列,
DISTINCT
仍然是最好的方法吗?
Or is a group by statement more appropriate?还是 group by 语句更合适?
(I'm using Postgres) (我正在使用 Postgres)
SELECT DISTINCT ON (product_id) * FROM products
That will return rows with distinct product_id
, and return all columns of those rows.这将返回具有不同
product_id
,并返回这些行的所有列。
If you care about the data in those other columns (eg you want the latest row for each product_id, rather than just random rows), you should also include an order:如果您关心其他列中的数据(例如,您想要每个 product_id 的最新行,而不仅仅是随机行),您还应该包含一个订单:
SELECT DISTINCT ON (product_id) * FROM products ORDER BY product_id, [other fields]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.