简体   繁体   English

使用选择不同的多个列,但所有列都必须是不同的

[英]using select distinct with multiple columns but all columns musnt be distinct

I need all columns in a table but two columns must be distinct. 我需要表中的所有列,但两列必须是不同的。 I used this code but It check all columns, but I only need two of them will be distinct. 我使用了这段代码,但是它检查了所有列,但是我只需要将其中的两个分开即可。 How can I satisfy this? 我该如何满足?

select distinct a.personalId, a.fileId, a.name, a.surname, a.address from my_table a

If I used the following code, I can not get the other columns: 如果使用以下代码,则无法获得其他列:

select distinct a.personalId, a.fileId from my_table a

Postgresql supports the DISTINCT ON syntax: http://www.postgresql.org/docs/current/interactive/sql-select.html Postgresql支持DISTINCT ON语法: http : //www.postgresql.org/docs/current/interactive/sql-select.html

select distinct on (a.personalId, a.fileId) a.personalId, a.fileId, a.name, a.surname, a.address
from my_table a

See Oracle equivalent of Postgres' DISTINCT ON? 看到Oracle等同于Postgres的DISTINCT ON吗? for how to do this in Oracle. 有关如何在Oracle中执行此操作。

What should happen if the other columns are different? 如果其他列不同,该怎么办? How should the database pick which value to show? 数据库应如何选择要显示的值? The answer is "it can't", and since it can't there is no syntax to do this (it's a logical error). 答案是“不能”,并且因为不能,所以没有语法可以这样做(这是一个逻辑错误)。

MySQL does have an extension where it will pick values randomly. MySQL确实有扩展,它将随机选择值。

select a.personalId, a.fileId, a.name, a.surname, a.address
from my_table a
group by a.personalId, a.fileId

But I don't recommend relying on this. 但是我不建议依赖于此。 You need to rethink the logic you are using. 您需要重新考虑所使用的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM