简体   繁体   中英

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

I have one image table and image view status table.

In each click of image I am tracking image view time. status. date time.. So in image view status table have more than one entry for one image.

I need to check whether one user already viewed one image or not.

So I write one query like this..

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

If I view one image three times its fetching 3 records. I need only one record to check whether user viewed the image or not.

So with out using DISTINCT or GROUP BY How can I fetch unique row of data.

Please help me.

you can use ORDER BY and LIMIT clause. to get most recent record you can use below query

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

to get old record

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

if you dont have datetime field remove ORDER BY clause which will give most recent modified record

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM