如果没有使用DISTINCT / GROUP BY,如何从mysql5表中获取唯一的一行数据


With out using DISTINCT / GROUP BY how to fetch unique row of data from mysql5 table?

我有一个图像表和图像视图状态表。

在每次点击图像我跟踪图像查看时间。的地位。日期时间. .因此,在图像视图状态表中,一个图像有多个条目。

我需要检查一个用户是否已经查看了一个图像。

所以我写了一个这样的查询…

select A.title, if(B.view_status='completed','completed','notviewed') from images A left join imgstatus_view B on (A.imgId=B.ImgId and A.fileId=B.fileID) Where userId=1 and imgId=121

如果我查看一个图像三次,它获取3条记录。我只需要一条记录来检查用户是否查看了图像。

所以不使用DISTINCTGROUP BY我如何获取唯一的数据行。

请帮帮我。

可以使用ORDER BY和LIMIT子句。要获取最近的记录,您可以使用下面的查询

select A.title, if(B.view_status='completed','completed','notviewed') from images A left join imgstatus_view B on (A.imgId=B.ImgId and A.fileId=B.fileID) Where userId=1 and imgId=121 ORDER BY datetimefield DESC LIMIT 0,1

获取旧记录

select A.title, if(B.view_status='completed','completed','notviewed') from images A left join imgstatus_view B on (A.imgId=B.ImgId and A.fileId=B.fileID) Where userId=1 and imgId=121 ORDER BY datetimefield LIMIT 0,1

如果你没有datetime字段,删除ORDER BY子句,它将给出最近修改的记录