简体   繁体   中英

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

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? for how to do this in 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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