简体   繁体   中英

DISTINCT in mysql query removing the records from resultset

DISTINCT in mysql query removing the records from resultset

I have three tables

TBL1       TBL2         TBL3
----       ------       --------    
tbl1_id    tbl2_id      tbl3_id                       
cid        fkcid        fkcid
           fktbl1_id    fktbl2_id

I have query to get records of TBL3

select distinct tbl3.* from TBL3 tbl3 
inner join TBL2 tbl2 on tbl2.tbl2_id = tbl3.fktbl2_id and tbl2.fkcid = tbl3.fkcid 
inner join TBL1 tbl1 on tbl1.tbl1_id = tbl2.fktbl1_id and tbl2.fkcid = tbl1.cid;

This query gives me around 1000 records.

But when I removes distinct from query it gives me around 1100 records. There is no duplicate records in table.Also I confirmed that these extra 100 are not duplicate.Please note That these extra 100 records are not found in query with distinct keyword .

Why this query is behaving unexpectedly.Please help me to understand more clearly and correct me if i am making mistake. Thank you

You have multiple records in tbl1 or tbl2 that map to the same tbl3, and since you're only selecting tbl3.* in your output, DISTINCT removes the duplication. To instead find what the duplicates are, remove the DISTINCT, add a COUNT(*) to the SELECT clause, and add at the end a GROUP BY and HAVING, such as:

select tbl3.*, count(*) 
from TBL3 tbl3  
inner join TBL2 tbl2 on tbl2.tbl2_id = tbl3.fktbl2_id and tbl2.fkcid = tbl3.fkcid  
inner join TBL1 tbl1 on tbl1.tbl1_id = tbl2.fktbl1_id and tbl2.fkcid = tbl1.cid 
group by tbl3.tbl3_id, tbl3.fkcid, tbl3.fktbl2_id having count(*) > 1;

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