我有这个代码,我希望有人帮助我将其更改为分组查询,从下面订购。
SELECT *
FROM dbo.users_pics INNER JOIN profile
ON users_pics.email = profile.email
Left Join photo_comment
On users_pics.u_pic_id = photo_comment.pic_id
WHERE users_pics.wardrobe = MMColParam
ORDER BY u_pic_id asc
我的意思是我有一组记录,我只想从下面选择一条记录。例如,如果我有10个名字“John”的记录,我想从10中选择最后一个“John”,然后其余的也跟着
答案 0 :(得分:0)
我将假设您的users
表包含单个用户,并且每个用户都有一个配置文件,您的photo_comment
表可以包含多个注释。
根据您的RDBMS
,您可以通过多种方式执行此操作。如果您使用支持SQL Server或Oracle等窗口函数的数据库,Row_Number
通常可以快速执行此操作。
对此的一般解决方案是使用MAX
聚合将表连接回自身。这取决于是否有一个字段来确定哪个记录是最大值。一般而言,这将是身份/自动号码字段或时间戳字段。
以下是使用photo_comment_id
作为确定列的基本概念:
SELECT *
FROM dbo.users_pics INNER JOIN profile
ON users_pics.email = profile.email
LEFT Join (
SELECT pic_id, MAX(photo_comment_id) max_photo_comment_id
FROM max_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_photo_comment_id = photo_comment.photo_comment_id
WHERE users_pics.wardrobe = MMColParam
ORDER BY u_pic_id asc
如果您的数据库支持ROW_NUMBER
,那么您也可以执行此操作(仍然使用photo_comment_id
字段):
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY photo_comment.pic_id
ORDER BY photo_comment.photo_comment_id DESC) rn
FROM dbo.users_pics INNER JOIN profile
ON users_pics.email = profile.email
LEFT JOIN photo_comment
ON users_pics.u_pic_id = photo_comment.pic_id
WHERE users_pics.wardrobe = MMColParam
) t
WHERE rn = 1
ORDER BY u_pic_id asc