计算每个项目的上下投票总和

时间:2014-01-27 20:26:27

标签: mysql sql

以下是我的表格,assetsasset_imagesvote。现在我需要为每个项目选择asset_id,filename,upvote,downvote。每个资产只有一个图像。那么,如何在不使用子查询的情况下为每个资产获取asset_id,filename,upvote和downvote? assets asset_images

vote

我期待输出像,

asset_id   filename    upvote downvote
1          5810.jpg    1      1
2          4357.jpg    1      0
3          435657.jpg  0      0

我尝试了这个查询,

SELECT a.asset_id, (
SELECT count( * )
FROM vote
WHERE asset_id = a.asset_id
) AS vote
FROM `assets` a
JOIN `asset_files` af
WHERE a.asset_id = af.asset_id

得到输出,

asset_id   filename    upvote downvote
1          5810.jpg    1      0
2          4357.jpg    0      0
3          5810.jpg    0      0

我不太擅长MySQL联接。所以,请帮忙。提前谢谢。

2 个答案:

答案 0 :(得分:4)

SELECT a.asset_id, f.filename,
       coalesce(SUM(v.vote = '1'), 0) as upvote,
       coalesce(SUM(v.vote = '-1'), 0) as downvote
FROM asset a
JOIN asset_files f ON a.asset_id = f.asset_id
LEFT JOIN vote v ON a.asset_id = v.asset_id
GROUP BY a.asset_id

DEMO

答案 1 :(得分:0)

试试这个。我假设vote表的Vote列中的值1,-1分别表示上下投票。

SELECT a.asset_id, 
    (
        SELECT count(*)
        FROM vote v
        WHERE asset_id = a.asset_id AND v.vote = 1
    ) AS upVote,
    (
        SELECT count(*)
        FROM vote v
        WHERE asset_id = a.asset_id AND v.vote = -1
    ) AS downVote
FROM `assets` a
    JOIN `asset_files` af
WHERE a.asset_id = af.asset_id