我有这个查询,我想计算一个未包含在查询中的字段,我不知道如何。我想要计算的字段被称为" pic_id"从表photo_comment
SELECT users_pics.wardrobe,
profile.fname,
users_pics.pic,
users_pics.u_pic_id,
users_pics.email,
users_pics.make,
users_pics.designer,
photo_comment.comment
FROM dbo.users_pics
INNER JOIN profile
ON users_pics.email = profile.email
LEFT Join (
SELECT pic_id,
MAX(comment_id) max_comment_id
FROM photo_comment
GROUP BY pic_id
) max_photo_comment
ON users_pics.u_pic_id = max_photo_comment.pic_id
LEFT JOIN photo_comment
ON max_photo_comment.pic_id = photo_comment.pic_id AND max_photo_comment.max_comment_id = photo_comment.comment_id
WHERE users_pics.wardrobe = MMColParam AND users_pics.email = MMColParam2
ORDER BY u_pic_id asc
答案 0 :(得分:1)
我假设您想知道“pic”有多少评论。我已将“COUNT(pic_id)count_pic_id”添加到左连接中的子查询中。希望这会有所帮助。
SELECT users_pics.wardrobe,
profile.fname,
users_pics.pic,
users_pics.u_pic_id,
users_pics.email,
users_pics.make,
users_pics.designer,
photo_comment.comment,
max_photo_comment.count_pic_id
FROM dbo.users_pics
INNER JOIN profile ON users_pics.email = profile.email
LEFT Join (SELECT pic_id, MAX(comment_id) max_comment_id, COUNT(pic_id) count_pic_id
FROM photo_comment
GROUP BY pic_id) max_photo_comment
On users_pics.u_pic_id = max_photo_comment.pic_id
LEFT Join photo_comment On max_photo_comment.pic_id = photo_comment.pic_id
AND max_photo_comment.max_comment_id = photo_comment.comment_id
WHERE users_pics.wardrobe = MMColParam AND users_pics.email = MMColParam2
ORDER BY u_pic_id asc
答案 1 :(得分:0)
您想计算一个不在您的选择列表中的字段吗?您需要将列添加到选择列表中以便对其进行计数,以及是否要查看计数值。
Select profile.fname,users_pics.pic,users_pics.u_pic_id,users_pics.email,
users_pics.make,users_pics.designer,photo_comment.comment
FROM dbo.users_pics
INNER JOIN profile ON users_pics.email = profile.email
LEFT Join (SELECT Count(DISTINCT pic_id) pic_id_cnt, pic_id, MAX(comment_id) max_comment_id
FROM photo_comment
GROUP BY pic_id ) max_photo_comment On users_pics.u_pic_id = max_photo_comment.pic_id
LEFT Join photo_comment On max_photo_comment.pic_id = photo_comment.pic_id AND max_photo_comment.max_comment_id = photo_comment.comment_id
WHERE users_pics.wardrobe = MMColParam AND users_pics.email = MMColParam2
ORDER BY u_pic_id asc