MySQL subquery required help
i am a beginner of MYSQL please help me.
i have a two table images and rate.
i want out put is imgID Rate.
image id as p.k in images table.
image is is foriegn key in rate table.
rate table sample data is
ImgID Rating
1 5
1 7
1 8
2 8
3 2
4 3
1 4
image table sample data is
ImgID Comment rate
1 good 7
2 bad 8
3 ok 8
4 fine 8
5 bad 7
out 开发者_高级运维put i required is
ImgId avg(rate from rate table when compared img id)
for example
ImgIf rate
-----------
1 6
2 8
3 2
4 3
i required subquery of this output.
thanks in advance
You don't need a subquery, you need an aggregation.
SELECT ImgID,
AVG(Rate) Rate
FROM RateTable
GROUP BY ImgID
If you want to include all images regardless of whether there is a rating:
SELECT i.ImgID,
AVG(r.Rate) Rate
FROM ImageTable i
LEFT JOIN
RateTable r
ON i.ImgID = r.ImgID
GROUP BY i.ImgID
精彩评论