Let's say I want to retrieve 100 records from a table called messages
, and I want to obtain them the following way:
1st message
100th message
2nd message
99th message
3rd message
98th message
(...)
Is there any way to do this efficiently? What would be the appropriate query? Or should I make a query to select the first 50, a query to select the last 50 and then merge the results?
This syntax does not exist as part of the merge statement. I also couldn't imagine how the query plan would look like. INSERT () VALUES (SELECT...) is not valid for the MERGE syntax. You cannot "trick" it.
So if there is a Source table and a Target table that are to be merged, then with the help of MERGE statement, all the three operations (INSERT, UPDATE, DELETE) can be performed at once. A simple example will clarify the use of MERGE Statement.
The MERGE statement basically works as separate INSERT, UPDATE, and DELETE statements all within the same statement. You specify a "Source" record set and a "Target" table and the JOIN condition between the two.
Try if your ID is a sequence of numbers:
First
SET @half = (SELECT MAX(id) FROM messages)/2;
Then
SELECT * FROM `messages` ORDER BY (IF(id<@half,@half*2-id,id-1)) DESC,id ASC;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With