mysql query showing 9 results
Question
i have a problem.
I'm running following query. I have only one record in my database but i'm getting 9 results.
SELECT c.id, c.rk
FROM cv AS c, employee AS e , cvCat AS cv_cat
WHERE c.status=1
AND c.empIDFK = e.id
AND cv_cat.categoryFK IN ( 17,18,19,38,39,40,41,44,45,46 )
AND cv_cat.cvFK = c.id
Can someone please let me know if they is any problem with this query. Why i'm getting 9 results rather then just 1 result.
This query should only display one record but its showing 9 results.
Solution
When you do
FROM cv AS c, employee AS e , cvCat AS cv_cat
You are doing an implicit join of the three tables. If you want to get distinct records you can add DISTINCT
after your select:
SELECT DISTINCT c.id, c.rk
FROM cv AS c, employee AS e , cvCat AS cv_cat
WHERE c.status=1
AND c.empIDFK = e.id
AND cv_cat.categoryFK IN ( 17,18,19,38,39,40,41,44,45,46 )
AND cv_cat.cvFK = c.id
OTHER TIPS
Use explicit joins:
SELECT c.id, c.rk
FROM cv c
INNER JOIN employee e ON e.id = c.empIDFK
INNER JOIN cvCat cv_cat ON cv_cat.cvFK = c.id
WHERE c.status = 1
AND cv_cat.categoryFK IN (17,18,19,38,39,40,41,44,45,46)
I think the 9 result row "issue" is based on your JOIN syntax, as that kind of implicit join will return all rows (of each table) as a joined result, since you are only pulling out c.id and c.rk it may look like MySQL sent the same result back 9 times.
Side Note: Implicit joins are being deprecated, using explicit joins, such as...
SELECT c.id, c.rk
FROM cv c
LEFT JOIN employee e ON c.empIDFK = e.id
LEFT JOIN cvCat cv_cat ON c.id = cv_cat.cvFK
WHERE...
Will help "future-proof" your code a bit and add a little more self-describing syntax to the whole query.