简体   繁体   中英

How to join two tables with redundant column value?

I have two tables named ServiceIOD and ServiceSubs and between them only one column named ShortCode is common. So, when I try to join these two tables to get the combined result for some given short code it is not giving me the correct output. May be it is because the ShortCode column is holding redundant data for both table. For example we can find shortcode=36788 multiple times in both tables for multiple rows. The query I tried so far is as below:

 SELECT distinct serviceIOD.keyword, 
        serviceIOD.shortcode 
   FROM serviceIOD 
        INNER JOIN serviceSubs 
            ON serviceIOD.shortcode = serviceSubs.shortcode 
            AND serviceIOD.shortcode = 36788

I would appreciate any sort of help from you all. Thank you.

UPDATE:

Explanation of incorrect output : I am getting total of 24 rows when I am joining by this query for shortcode 36788 but when I query separately in two tables for the shortocde 36788 I get 24 rows for ServicesIOD table and 3 rows for ServicesSubs table. All together 27 rows. But when I join with the query above I get only 24 rows.

Try this code.Usually the UNION is avoiding duplication entries.

(SELECT serviceIOD.keyword, 
serviceIOD.shortcode 
FROM serviceIOD) 
UNION (select * from serviceSubs)
WHERE serviceIOD.shortcode = 36788

The Inner Join and the shortcode 36788, filters rows that match between the two tables, and knowing that you've already made a test on the serviceSubs table and got 3 rows, the result of the join will be 3 rows too, but then you perform a select distinct on both keyword and shortcode , so this query looks for a distinct keyword where the shortcode value is 36788, that's why you get 24 rows.

Let me know if i'm wrong so I can delete it.

I have solved this problem with this following query:

 SELECT serviceIOD.keyword, 
 serviceIOD.shortcode 
 FROM serviceIOD where shortcode = 36788
 UNION select serviceSubs.keyword, 
 serviceSubs.shortcode  from serviceSubs where shortcode = 36788

Thank you everyone for taking your valuable time to help me on my problem. And special thanks to @Optimuskck as I got my answer idea from his suggested answer.

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