Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner join returning more rows then exist in tables

Till today my thoughts about the inner join were it will return the minimum number of rows that exist in tables satisfying a joining condition.

Ex. if table A contains 4 rows and table B contains 7 rows . i was expecting that 4 rows can be the maximum output if they satisfy the joining condition.

I just wrote an sp in which i was creating two temporary tables and was populating them. then i took an inner join of them but returning more rows (In my case 29 rows were returned i was expecting 4) After some search i found this link

which confirms that i can happen but i still wonder what are my options to limit the returned result.

Below is my stored procedure.

ALTER PROCEDURE [dbo].[GetDDFDetailOnSiteCol]
@siteId int,
@colNum int
AS
BEGIN
SET NOCOUNT ON;

create Table #portDetail
(
ddfId int,
portDetail nvarchar(50),
siteId int
)
Insert into #portDetail SELECT  ddf.id,  ddf.portDetail, site.Site_ID  from site
        inner join ddf ON site.Site_ID = ddf.siteCodeID 
        where ddf.siteCodeID = @siteId and ddf.colNo= @colNum
        order by colNo,blockNum,portRowNum,portColNum

create Table #portAllocationDetail
(
assigned_slot nvarchar(50),
siteId int
)
Insert into #portAllocationDetail 
SELECT  dbo.portList.assigned_slot, dbo.site.Site_ID
FROM dbo.portList INNER JOIN
 dbo.site ON dbo.portList.siteCodeID = dbo.site.Site_ID
 where dbo.site.Site_ID = @siteId

--select * from #portAllocationDetail   
Select #portDetail.ddfId,#portDetail.portDetail,#portAllocationDetail.siteId,#portAllocationDetail.assigned_slot FROM #portDetail 
INNER JOIN #portAllocationDetail 
ON
#portDetail.siteId = #portAllocationDetail.siteId
END
like image 662
Shah Avatar asked Sep 12 '12 13:09

Shah


People also ask

Why do multiple table joins produce duplicate rows?

Using an Incomplete ON Condition. Unwanted rows in the result set may come from incomplete ON conditions. In some cases, you need to join tables by multiple columns. In these situations, if you use only one pair of columns, it results in duplicate rows.

Why LEFT join increases number of rows in SQL?

There are two line items for ID 1003 in the second table, so the result of the join will be 2 line items. So, if your secondary tables have more than one row for the key you're joining with, then the result of the join will be multiple rows, resulting in more rows than the left table.

Does inner join giving duplicate records?

The answer is yes, if there are any. If there are duplicate keys in the tables being joined.


1 Answers

An inner join repeats each matching row in TableB for each row in TableA. So if there are 4 rows in TableA, and 7 in TableB, the maximum rowcount is 28.

Example at SQL Fiddle.

like image 200
Andomar Avatar answered Oct 04 '22 18:10

Andomar