JOIN is returning Multiple results when only One record matches the WHERE clause?
Question
SELECT images.filename, slugs.name FROM images, slugs
WHERE images.status = 1 AND slugs.name = 'test'
However, I only have 1 record where slugs.name = 'test'
is true!
What is going on?
Solution
Others are pointing out what you have wrong (that you're getting a cartesian join), but not how to fix it. We need to know how rows in images
are related to rows in slugs
. If, say, there's a column called BingoID
in both, that should match, then something like:
SELECT images.filename, slugs.name FROM images, slugs
WHERE images.status = 1 AND slugs.name = 'test' AND images.BingoID = slugs.BingoID
or,
SELECT images.filename, slugs.name
FROM images inner join slugs
ON images.BingoID = slugs.BingoID
WHERE images.status = 1 AND slugs.name = 'test'
OTHER TIPS
but you probably have two images.status = 1.
They way you wrote it, it is almost a full join, a Cartesian multiplication.
How are the images and slugs tables related? I think you need to add an inner join, as the query you have will return as many slugs with the name "test" as entries in the images table.
This is because you have more than one images.status = 1
:)
Your query match all rows from table images
having status = 1
with all rows from table slugs
having name = 'test'
.
There's a good chance it's doing an implicit natural join because you're selecting from two tables like that.
It makes a cross join and images table would have more than one rows then a new table is created having rows multiplication of no. of rows of both tables due to which this query giving more than one results.
You should try right outer join to get single result try this
SELECT images.filename, slugs.name FROM images right outer join slugs
on images.ID = slugs.ID
where images.status = 1 AND slugs.name = 'test'