简体   繁体   English

除了在一列中具有非唯一值的行之外,抓取表中的所有行列

[英]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.

相关问题 PSQL select 具有非唯一列的所有行 - PSQL select all rows with a non-unique column SQL - 返回所有行,但是非唯一行合并为一个(算术执行)? - SQL - return all rows, however non-unique rows are merged into one (arithmetic performed)? 当按其他列分组时,如何在特定列中具有非唯一值的 select 行? - How to select rows with non-unique values in a specific column when grouped by other columns? MySQL-如何将非唯一行转换为列并保持完整性? - MySQL - How to convert non-unique rows into columns and maintain integrity? SQL - 为每个非唯一 ID 选择具有不同一列的行 - SQL - Select rows with distinct one column for each non-unique ID 用附加条件计数表中的非唯一行 - counting non-unique rows in table with additional criteria SQL删除每个唯一值的最后N行以外的所有行 - SQL DELETE all rows apart from last N rows for each unique value 从非唯一标识符将列信息从一个表导入到另一个表 - Import Column info from one table to another from non-unique identifier 删除非唯一ID行 - Remove non-unique ids rows Oracle:将列移至新表,消除原表中剩余的非唯一行,同时保持两个表之间的外部关系 - Oracle: Move column to new table, eliminate non-unique rows remaining in original table while maintaining foreign relationship between two tables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM