Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an INNER JOIN to a query should not increase the number of rows returned right?

I have a query like the following that returns the correct number of rows that I would expect. (It has to match a similar query that returns the same data sets but with different associated info from other related tables.

SELECT *
FROM LK
INNER JOIN STC ON LK.V = STC.VI
LEFT OUTER JOIN BC ON LK.BC = BC.ID
LEFT OUTER JOIN K AS LT ON ISNULL(BC.ZA, LK.VH) = LT.KNN
WHERE
    LT.KI IS NOT NULL AND LT.KS = 0
  OR 
    LT.KI IS NULL 
ORDER BY
  LK.Z

But as soon as I add other inner joins I actually get more rows back. I thought an inner join only returns rows when information is found in both sides of the join, so I expected to get either the same or less rows back. But I get around twice as much.

For example:

SELECT *
FROM LK
INNER JOIN STC ON LK.V = STC.VI

INNER JOIN VK ON LK.V = VK.ID
INNER JOIN K AS A ON VK.AIN = A.KNN

LEFT OUTER JOIN BC ON LK.BC = BC.ID
LEFT OUTER JOIN K AS LT ON ISNULL(BC.ZA, LK.VH) = LT.KNN
WHERE
    LT.KI IS NOT NULL AND LT.KS = 0
  OR 
    LT.KI IS NULL 
ORDER BY
  LK.Z

Does this make sense? How can adding two more inner joins result in more rows being returned?

And more to the point of my actual problem, how I can adjust the second query so it returns the same rows as the first query but with the extra columns from the joined tables?

like image 572
Kurt Avatar asked Aug 18 '10 07:08

Kurt


People also ask

Can inner join increase the number of rows?

Inner Join can for sure return more records than the records of the table. Inner join returns the results based on the condition specified in the JOIN condition. If there are more rows that satisfy the condition (as seen in query 2), it will return you more results.

How many rows are returned in inner join?

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.

Will LEFT join increases number of rows?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.

What is true about not inner join?

5) What is true about NOT INNER JOIN? a) It is a JOIN which restricts INNER JOIN to work.


1 Answers

if there's more than one VK per LK then it will increase the # of rows. I don't understand your schema enough to fix it though.

like image 51
tenfour Avatar answered Oct 11 '22 16:10

tenfour