我的应用程序中使用了几个表。一个维护产品列表,另一个维护对这些项目的评论,另一个包含这些项目的星级评级,最后一个包含这些项目的购买。我的表看起来像这样:
tbl_item:
---------
id INT (primary key)
name VARCHAR (product name)
tbl_comment:
------------
id INT (primary key)
item_id INT (foregin key -> tbl_item.id)
commenttext VARCHAR
tbl_rating:
-----------
id INT (primary key)
item_id INT (foreign key -> tbl_item.id)
rating DOUBLE
tbl_purchases:
--------------
id INT (primary key)
item_id INT (foreign key -> tbl_item.id)
我想执行一个返回以下内容的查询:
* The design ID
* The average rating
* The number of comments
* The number of purchases
我有类似的东西,但它返回不正确的数据:
SELECT d.id ,
COUNT(tbl_purchases.id) AS purchase_count,
COUNT(tbl_comment.id) AS comment_count,
AVG(tbl_rating.rating) AS item_rating,
FROM tbl_item d
LEFT JOIN tbl_purchases ON tbl_purchases.item_id = d.id
LEFT JOIN tbl_comment ON tbl_comment.item_id = d.id
LEFT JOIN tbl_rating ON tbl_rating.id = d.id
GROUP BY d.id;
我发现我的COUNT()列为两列返回相同的值,这绝对不正确。很明显,我在我的连接或GROUP BY中做错了,但我不完全确定是什么。我是一个Java人,而不是SQL人,所以我不确定这个SELECT语句中出了什么问题。
任何人都可以帮我构建这个查询吗?有没有办法以这种方式跨多个不同的表执行此聚合查询?谢谢!
答案 0 :(得分:5)
试试这个:
SELECT d.id ,
COALESCE(t.purchase_count,0) as purchase_count,
COALESCE(c.comment_count,0) as comment_count,
r.item_rating,
FROM tbl_item d
LEFT JOIN (SELECT item_id, COUNT(1) as purchase_count from tbl_purchases group by item_id) as t on t.item_id = d.id
LEFT JOIN (SELECT item_id, COUNT(1) as comment_count from tbl_comment group by item_id) as c ON c.item_id = d.id
LEFT JOIN (SELECT item_id, AVG(rating) as item_rating from tbl_rating group by item_id) as r ON r.item_id = d.id;
答案 1 :(得分:1)
使用count(distinct(tbl_purchases.id))
可以解决您的问题,而无需其他人提供的更复杂的查询(但也更正确)。
答案 2 :(得分:0)
它在某种程度上取决于你正在使用什么数据库,但这在PostgreSQL中有用:
SELECT d.id , p.count, c.count, AVG(I.rating)
FROM tbl_item d
JOIN ( SELECT count(id), item_id as id from tbl_purchases ) as P
USING (id)
JOIN ( SELECT count(id), item_id as id from tbl_comment ) as C
USING (id)
LEFT JOIN tbl_rating as I
ON tbl_rating.id = d.id
GROUP BY d.id
;