sorry about the title, I’m not sure how to even describe this, which makes it even harder to search for a solution.
I have a table which has many answers:
CREATE TABLE `answers` (
`a_id` int(11) NOT NULL auto_increment,
`p_id` int(11) NOT NULL default '0',
`q_id` int(11) NOT NULL default '0',
`user_id` int(11) NOT NULL default '0',
`correct` int(1) NOT NULL default '0',
`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`a_id`)
) ;
I need to select a q_id from a specific user_id and p_id where correct = 0, but only where a more recent row from the same user_id and p_id’s correct field is not 1.
I can group by id, but am unsure how to eliminate groups where the top correct != 0
Thanks in advance. I’ve found many helpful answers here and am looking forward to contributing where I can.
EDIT: Currently the query as stands, but takes 6 secs to execute:
From both your answers I have query that works, but takes 6 secs to execute!
SELECT a.q_id FROM answers a
JOIN (SELECT b.q_id, MAX(b.a_id) as a_id, b.correct
FROM answers b
WHERE b.correct = 1
AND b.user_id = 1
AND b.p_id = 22
GROUP BY b.q_id) c ON a.q_id = c.q_id
AND a.a_id > c.a_id
WHERE a.correct = 0
AND a.user_id = 1
AND a.p_id = 22
LIMIT 1
With no JOIN they take .26 secs. and .45 secs to execute How can I make it more efficient?
Is there another way to select the most recent correct = 0 row where a prev correct = 1 row does not exist?
Thanks for all your help!
This query seems to be working best. It’s my edited answer, updated with ordering the a.a_id and limiting the return to one.
Thanks very much to OMG Ponies and Nirmal for helping me through this. Sorry if answering my own question is bad form here, but I comprised my query based on what I learned from you both.
Thanks again!!!