简体   繁体   English

从 sql 的结果中删除重复项

[英]Remove duplicates from result in sql

i have following sql in java project:我在 java 项目中有以下 sql :

select distinct * from drivers inner join licenses on  drivers.user_id=licenses.issuer_id
        inner join users on drivers.user_id=users.id 
        where (licenses.state='ISSUED' or drivers.status='WAITING')
        and users.is_deleted=false 

And result i database looks like this:结果 i 数据库如下所示: 在此处输入图像描述

And i would like to get only one result instead of two duplicated results.我只想得到一个结果而不是两个重复的结果。 How can i do that?我怎样才能做到这一点?

Solution 1 - That's Because one of data has duplicate value write distinct keyword with only column you want like this解决方案 1 - 那是因为其中一个数据具有重复值写入不同的关键字,只有你想要的列

Select distinct id, distinct  creation_date, distinct  modification_date from 
YourTable

Solution 2 - apply distinct only on ID and once you get id you can get all data using in query解决方案 2 - 仅在 ID 上应用 distinct,一旦获得 id,您就可以在查询中使用所有数据

select * from yourtable where id in (select distinct id from drivers inner join 
 licenses 
 on drivers.user_id=licenses.issuer_id
 inner join users on drivers.user_id=users.id 
 where (licenses.state='ISSUED' or drivers.status='WAITING')
 and users.is_deleted=false )

Enum fields name on select, using COALESCE for fields which value is null. select 上的枚举字段名称,对值为 null 的字段使用 COALESCE。

usually you dont query distinct with * (all columns), because it means if one column has the same value but the rest isn't, it will be treated as a different rows.通常您不会使用 *(所有列)进行不同的查询,因为这意味着如果一列具有相同的值但 rest 不是,它将被视为不同的行。 so you have to distinct only the column you want to, then get the data所以你必须只区分你想要的列,然后获取数据

I suspect that you want left join s like this:我怀疑你想要这样的left join

select *
from users u left join
     drivers d
     on d.user_id = u.id and d.status = 'WAITING' left join
     licenses l
     on d.user_id = l.issuer_id and l.state = 'ISSUED'
where u.is_deleted = false and
      (d.user_id is not null or l.issuer_id is not null);

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

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