TheLettuceMaster
TheLettuceMaster

Reputation: 15734

Attempting to Join 3 tables in MySQL

I have three tables that are joined. I almost have the solution but there seems to be one small problem going on here. Here is statement:

SELECT items.item,
COUNT(ratings.item_id) AS total,
COUNT(comments.item_id) AS comments,
AVG(ratings.rating) AS rate
FROM `items`
LEFT JOIN ratings ON (ratings.item_id = items.items_id)
LEFT JOIN comments ON (comments.item_id = items.items_id)
WHERE items.cat_id = '{$cat_id}'  AND items.spam < 5
GROUP BY items_id ORDER BY TRIM(LEADING 'The ' FROM items.item) ASC;");

I have a table called items, each item has an id called items_id (notice it's plural). I have a table of individual user comments for each item, and one for ratings for each item. (The last two have a corresponding column called 'item_id').

I simply want to count comments and ratings total (per item) separately. With the way my SQL statement is above, they are a total.

UPDATE: 'total' seems to count ok, but when I add a comment to 'comments' table, the COUNT function affects both 'comments' and 'total' and seems to equal the combined output.

Upvotes: 0

Views: 121

Answers (2)

StuckAtWork
StuckAtWork

Reputation: 1633

Problem is you're counting results of all 3 tables joined. Try:

SELECT i.item,
r.ratetotal AS total,
c.commtotal AS comments,
r.rateav AS rate
FROM items AS i
LEFT JOIN
    (SELECT item_id, 
    COUNT(item_id) AS ratetotal, 
    AVG(rating) AS rateav 
    FROM ratings GROUP BY item_id) AS r 
ON r.item_id = i.items_id
LEFT JOIN
    (SELECT item_id, 
    COUNT(item_id) AS commtotal 
    FROM comments GROUP BY item_id) AS c
ON c.item_id = i.items_id
WHERE i.cat_id = '{$cat_id}'  AND i.spam < 5
ORDER BY TRIM(LEADING 'The ' FROM i.item) ASC;");

In this query, we make the subqueries do the counting properly, then send that value to the main query and filter the results.

Upvotes: 1

Adriano Carneiro
Adriano Carneiro

Reputation: 58595

I'm guessing this is a cardinality issue. Try COUNT(distinct comments.item_id)

Upvotes: 0

Related Questions