I have a problem with implementing a module where one project
can belong to multiple categories
. Example: project \"PHP Programmer\" belongs to cat
You can also rewrite this as an "IN" to get around duplicates:
SELECT projects.*
FROM projects
where projects.id in (select project_id
from projects_category
WHERE pojects_category.category_id IN (1,3,11)
) and
projects.id='94'
The "in" prevents duplicates from forming when you are using joins for filtering records.
No, this is fine. This is just one of the rare cases when you want to use the DISTINCT
key word to remove duplicates.
In this case this is justified by the fact that the logic of the query is correct, even though it returns more than one row. Many times one can see the usage of DISTINCT
when actually the logic of the query is wrong.
Side-note:
WHERE
clause other than IS NULL/IS NOT NULL
would make any LEFT JOIN
on this same table reference turn to an INNER JOIN
, as for the final resultset behaviour. (see this: https://stackoverflow.com/a/15483895/1291428)you ought not use GROUP BY
to simulate the effect of DISTINCT
, for 2 reasons:
1/ This is just not the purpose. One of the effects of GROUP BY
is to eliminate duplicates, but its main purpose is to group rows according to a certain set of criteria, in order to apply some analytic calculations/operations on them.
2/ GROUP BY
also ORDER BY
the results (in mysql), which is not necessarly what you want and in that case slows down the execution. Please, just ensure appropriate use of what the engines are providing, that's always better from the point of view of forward compatibility. (anticipating that what you include as granted is actually not)
regards.