I need a query that, when the conditions are met, takes into account the number of occurrences of a certain record in COUNT(*).
My non-working solution:
SELECT t.name, t.tovar_id, p.path FROM `tovars` t, `tovarPicture` p WHERE t.nomGroup = :group AND p.tovar_id = t.tovar_id AND p.tovarPicture_id IS NULL AND COUNT(SELECT * FROM knotConnections WHERE tovar_id = t.tovar_id) = 0
2
Answers
If the count must always be zero (ie, there are no matching records in the other table) then you could use NOT EXISTS or an anti-join:
If you need more flexibility – you want the count to be a specific number – then you could use COUNT in a HAVING clause:
Rob Eyre’s answer shows the usual ways of doing this, but what you had was close to working, you just need to change
to
When you want to use the value of a subquery it in an expression, you just have to enclose it in parens (and make sure it is returning the single value you want, not more than one value or more than one row).