Reputation: 6139
I need some help to get the desired results, which would in this case, be 7 (the number of rows in the products table that would match).
What I am instead getting is 7 rows with a count based on the the number of rows returned in the LEFT JOIN.
SELECT count(p.id) as theCount
FROM products p
left join tablea a on p.id = a.productId
left join tableb b on p.id = b.productId
WHERE (a.col = 'val' or b.col = 'val')
group by p.id
If I do not group by p.id, I get back 28 rows, which is all of the rows from the LEFT JOIN.
I know it's something simple, but I can't figure it out.
Thanks.
Upvotes: 0
Views: 3343
Reputation: 7838
You shouldn't join the one-to-many relationships if all you want is the count of products
.
Put your filter condition in the WHERE
clause.
SELECT count(*) as theCount
FROM products p
WHERE p.id IN (
SELECT a.productId
FROM tablea a
WHERE a.productId = p.id AND a.col = 'val'
UNION
SELECT b.productId
FROM tableb b
WHERE b.productId = p.id AND b.col = 'val'
)
Upvotes: 2
Reputation: 360702
select count(distinct p.id)
, perhaps? Since you're pulling from two different tables, you're going to get a mismash of (p.id, a.col, b.col)
being (xxx, null, yyy)
and (xxx, yyy, null)
Upvotes: 3