Click here to Skip to main content
15,915,800 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi
I have to retrieve required field from 3 tables and the common field is NRIC in all the 3 tables. when I am using the below query I am getting duplication.

SQL
select distinct A._qsn,A._queueno,A._NRICNo,B._Name,B._race,B._block,B._unitno,B._street,B._handphone,B._gender,B._race,B._language,C._letterNo,A._status,A._wentHome,A._remarks,A._caseType,A._welfare,A._welfareSave from tbQueue A, tbPeopleResident B ,tbLetterHistory C where A._NRICNo=B._NRICNo and B._NRICNo = C._NRICNo


Your suggestion's will be appreciated.
Posted

Hi,

SQL
SELECT
 A._qsn,A._queueno,A._NRICNo,B._Name,B._race,B._block,B._unitno,B._street,B._handphone,B._gender,B._race, B._language, C._letterNo, A._status ,A._wentHome, A._remarks, A._caseType, A._welfare, A._welfareSave
from tbQueue A
    INNER JOIN tbPeopleResident B ON A._NRICNo=B._NRICNo
    INNER JOIN tbLetterHistory C ON A._NRICNo=C._NRICNo


If your data is proper stored in database then you never need to use DISTINCT keyword in your query.
If your table B or C has multiple values then you will get more then one row for each NRICNo but all fields will not be unique because table B or C will have different values.
 
Share this answer
 
You're getting duplicated data because of not defined joins between tables: from tbQueue A, tbPeopleResident B ,tbLetterHistory C

Try to replace your query with:
SQL
SELECT DISTINCT A._qsn, A._queueno, A._NRICNo, B._Name, B._race, B._block, B._unitno, B._street, B._handphone, B._gender, B._race, B._language, C._letterNo, A._status, A._wentHome, A._remarks, A._caseType, A._welfare, A._welfareSave
FROM tbQueue AS A LEFT JOIN tbPeopleResident AS B ON A._NRICNo=B._NRICNo LEFT JOIN tbLetterHistory AS C ON B._NRICNo = C._NRICNo


You need to test it with defferent types of joins: LEFT, RIGHT, INNER (with OUTER option), but first, please, refer the below links:
T-SQL Basics: Different Types of Joins[^]
T-Sql Joins (w3schools)[^]
T-SQL Joins (msdn)[^]
Using Joins (msdn)[^]
and the best of all ;)
Visual Representation of SQL Joins[^]
 
Share this answer
 
Comments
Lancy.net 25-May-13 9:55am    
Thank you for your solution stll I am getting the same..
will try again and update u..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900