I’ve got two tables related by a field called ‘status’. With table2.location having a value of ‘texas’, there are 20 instances of table2.status having a value of ‘good’.
That is, the following query returns 20 rows of table2.status = ‘good’.
[A] SELECT table2.status FROM table2 WHERE table2.location = 'texas';
Further, there are 50 unique table1.id’s with table1.status = ‘good’.
That is, the following query returns 50 rows of unique table1.id’s.
[B] SELECT table1.id FROM table1 WHERE table1.status = 'good';
Now, when I run the following query:
[C] SELECT table1.id FROM table1 LEFT JOIN table2 ON table1.status = table2.status WHERE table2.location = "texas";
I would expect it to return the 50 rows of unique id’s. However, it is actually returning the 50 rows of unique id’s 20 times (ie. I get 1000 rows returned).
The quick fix I did was to simply execute SELECT DISTINCT table1.id… which then just returns one set of 50 rows (not 20 sets of 50 rows).
However, I’d like to know why I’m seeing this behahvior – maybe there is something wrong with my query [C] ?
Thanks!
Your query has two problems
First when you usae a left join a condition on the second table must be in the ON clause not the where clause or you convert the left join to an inner join (Since the condition must be met)
So your query should start looking like this:
Now your next problem is that status is unlikely to be the thing you actually want to join on. To help you get the results you want though, we would need to see the table structure of the two tables.