以下是我的表格,assets
,asset_images
和vote
。现在我需要为每个项目选择asset_id,filename,upvote,downvote。每个资产只有一个图像。那么,如何在不使用子查询的情况下为每个资产获取asset_id,filename,upvote和downvote?
我期待输出像,
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联接。所以,请帮忙。提前谢谢。
答案 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
答案 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