I'm going to throw a towel with this.
Preface: I want to make this work with any N, but for simplicity I set N to 3.
I have a query (in particular, MySQL) that should retrieve data from a table and sort based on the top three values from this table and then refer to other sorting criteria.
So basically I have something like this:
SELECT tbl.id FROM tbl1 AS maintable LEFT JOIN tbl2 AS othertable ON maintable.id = othertable.id ORDER BY othertable.timestamp DESC, maintable.timestamp DESC
This is all a basic tutorial. But the problem is that I need the first ORDER BY clause to get only the three largest values in othertable.timestamp, and then return to maintable.timestamp.
In addition, executing the LIMIT 3 subquery for other tables and joining it is not necessary, since this should work with an arbitrary number of WHERE conditions applied to the main table.
I was almost able to get it to work with this approach based on user variables, but it fails because it does not take into account ordering, so it will find FIRST three other table values:
ORDER BY ( IF(othertable.timestamp IS NULL, 0, IF( (@rank: =@rank +1) > 3, null, othertable.timestamp ) ) ) DESC
(with @rank: = 0 preceding the statement)
So ... any advice on this? I'm going crazy with this problem. Another parameter that I have for this is that since I am only modifying an existing (significantly complex) request, I cannot make an external external request. In addition, as already noted, I am in MySQL, so any solutions using the ROW_NUMBER function are unfortunately not available.
Thanks to everyone in advance.
EDIT. Here are some examples of timestamped data that are suppressed to prime integers to illustrate what I need:
maintable id timestamp 1 100 2 200 3 300 4 400 5 500 6 600 othertable id timestamp 4 250 5 350 3 550 1 700 => 1 3 5 6 4 2
And if for some reason we add WHERE NOT maintable.id = 5 to the query, this is what we should get:
1 3 4 6 2
... because now 4 is among the top 3 values in another table, referring to this set.
So, as you can see, the row with id 4 from another table is not included in the order, since it is the fourth in descending order of timestamp values, so it returns to ordering by the base timestamp.
The real world’s need for this is as follows: I have the content in the “maintable”, and “othertable” is basically a marker for the contained content marked “assigned date”. I have an idea where I should float the last 3 recognized elements at the top, and the rest of the list is a reverse chronological list.