简体   繁体   中英

Inner join between two tables with same count values

I have been working on this issue since 2 days now.

I have two tables created by using SQL Select statements

SELECT (


) Target

INNER JOIN

SELECT (


) Source

ON Join condition 1
AND Join condition 2
AND Join condition 3
AND Join condition 4
AND Join condition 5

The target table has count value of 10,000 records. The source table has count value of 10,000 records.

but when I do an inner join between the two tables on the 5 join conditions

I get 9573 records.

I am basically trying to find a one to one match between source and target table. I feel every field from target matches every field in source.

Questions:

  1. Why does my inner join give less records even if there are same value of records in both tables?
  2. If it is expected, how can I make sure I get the exact 10,000 records after the join condition?

There's some really good articles about the different joins out there. But it looks like you'd be interested in left joins. So if it exists in Target, but not in Source, it will not drop the record.

So, it would be:

SELECT(...) Target
LEFT OUTER JOIN
SELECT(...) Source
   ON cond1 and cond2 and cond3 and cond4 and cond5

Give that a shot and let me know how it goes!

1) An INNER JOIN only outputs the rows from the JOINING of two tables where their joining columns match. So in your case, Join Condition1 may not exist in rows in both tables and therefore some rows are filtering out.

2) As the other poster mentioned a left join is one way. You need to look which table source or target you want to use as your master ie start from and return all those rows. You then left join the remaining table based on your conditions to add all the columns where you join conditions match.

It's probably better if you give us the tables you are working on and the query\\results you are trying to achieve.

Sometime you need to rely on logical analysis rather than feelings. Use this query to find the fields that do not match and then work out your next steps

SELECT 
Target.Col1,Source.Col1,
Target.Col2,Source.Col2,
Target.Col3,Source.Col3
FROM
(

) Target
FULL OUTER JOIN
(

) Source
ON  Target.Col1=Source.Col1
AND Target.Col2=Source.Col2
AND Target.Col3=Source.Col3
WHERE (
Target.Col1 IS NULL 
OR Source.Col1 IS NULL 
OR Target.Col2 IS NULL 
OR Source.Col2 IS NULL 
OR Target.Col3 IS NULL
OR Source.Col3 IS NULL
)

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