Mysql : last five records if having same value


Mysql : last five records if having same value



I searched a lot and tried many queries but not getting satisfied answer. So like to ask.



I am looking for last 5 records from mysql table if having same value otherwise not.



Something like if col_n is having same value x from last 5 records then count otherwise not. But I am not able to figure out how to write query for this ?


if col_n is having same value x from last 5 records then count otherwise not


SELECT count(col_n)
from track if(last five col_n = 'ok')
WHERE col_a = 'value1' AND col_b = 'value2'



enter mysql table records





show the queries you tried please
– Fanie Void
2 days ago





Please write a query which you tried then we try to modify that.
– Gufran Hasan
2 days ago





I never wrote if statement in mysql so have no idea what to write ?
– Jhon A
2 days ago





from last 5 records ... this only makes sense with regard to some order in your table. Please add some sample data to make this a real question.
– Tim Biegeleisen
2 days ago


from last 5 records





Okay @JhonA, please try my answer
– Gufran Hasan
2 days ago




1 Answer
1



Please try this:


SELECT p.*
FROM
( SELECT *
FROM demo ORDER by id DESC
LIMIT 5
) AS p
JOIN
( SELECT COUNT(*) AS cnt
FROM
( SELECT 1
FROM demo
LIMIT 5
) AS tmp
) AS c
ON c.cnt = 5 WHERE p.name='x'





please check i attached an image of mysql table
– Jhon A
2 days ago





Hey, @JhonA, please try this query as I updated my answer
– Gufran Hasan
2 days ago





Sorry Gufran Hasan , not working. First 2-3 trials it shows result but after that it is giving no results i tested and checked every variables are right.
– Jhon A
2 days ago





I got another solution with the help of PHP , to retrieve all last 5 records of the user and check if they are same. If same then do action otherwise not. So if there is no direct solution through mysql command then PHP i will implement.
– Jhon A
2 days ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift