Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to merge in a SELECT in SQL?

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?

like image 382
federico-t Avatar asked Dec 03 '11 22:12

federico-t


People also ask

Can we use select in MERGE statement?

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.

Can we use MERGE in SQL?

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.

How do you MERGE records in SQL?

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.


1 Answers

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;
like image 159
Paulo H. Avatar answered Oct 06 '22 20:10

Paulo H.