1

I have a table like this

CREATE TABLE `filelog` (
  `date_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `file` varchar(200) DEFAULT NULL,
  `action` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1

action could have values 'upload' and 'delete'

I have a list view where the files that are uploaded are displayed for deletion. The problem is that the same file could be deleted and again uploaded numerous times and this is a log table where all these action are inserted. So the query should display the files with action 'upload' where the most recent action 'delete' took place before the 'upload' action.

1
  • A question with no question-mark! why don't use order by date_time desc ? Commented Mar 18, 2011 at 6:42

2 Answers 2

1

Sounds like your requirement is logically equivalent to

"Show the most recent entry for each given file IFF this most recent entry is an upload"

Is that correct? If so...

SELECT F1.*
FROM filelog F1
WHERE F1.action = 'upload' AND F1.date_time =
          SELECT max(F2.date_time)
          FROM filelog F2
          WHERE F2.file = F1.file

You still want it if there has NEVER been a deletion right?

Sign up to request clarification or add additional context in comments.

11 Comments

If the user has re-uploaded that file twice or more, it will miss a delete action. Questionable to business logic.
can you give a counterexample where these are not equivalent? i dont understand what the issue is
The issue could be when the user has 10 update actions in row, and no delete action for these. Your query will list these too.
Yes, I am talking about that. As said it's Questionable to business logic
you think we only want to list the most recent upload if it immediately follows a deletion?
|
0

Try this one:

SELECT * 
FROM   filelog f 
       JOIN (SELECT FILE, 
                    max(date_time) 
             FROM   filelog 
             WHERE  ACTION = 'delete' 
             GROUP  BY FILE) d 
         ON d.FILE = f.FILE 
            AND d.date_time < f.date_time 
WHERE  ACTION = 'update' 

This reads the most recent deletes on files in the derived table. And joins the outer table with these.

you need indexes on

  • (file,date_time)

1 Comment

Rather than using the order by, you probably want to use max(date_time) as date_time in the select.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.