How to make an expression inside a select statement without returning it as a column?

I have a series of rows from a database that I want to insert into another database. Since there are quite a few rows, I want to use the INSERT .. SELECT ... construct in mysql. The statement I am trying to run is as follows:

set @rank := 1; set @currpoints := 0; set @currgroupcount := 0; 
  SELECT id, @rank := if( @currpoints = points, @rank , @rank + @currgroupcount )
  AS rank, 
  @currgroupcount := if( @currpoints = points, @currgroupcount +1, 1 ) , @currpoints := 
  points
FROM characters
ORDER BY points DESC , name
LIMIT 0 , 30

The problem is that I cannot insert the selected rows into the database when the result has more than two columns. Is there a way to make these necessary increments without returning column expressions? If this is not possible, you know what I can do as an alternative and still be able to get a performance boost that involves using INSERT .. SELECT ... construct?

+3
3
INSERT
INTO new_characters (id, name)
SELECT id, name
FROM (
  SELECT id,
  @rank := if( @currpoints = points, @rank , @rank + @currgroupcount ) AS rank, 
  @currgroupcount := if( @currpoints = points, @currgroupcount +1, 1 ),
  @currpoints := points
  FROM characters
  ORDER BY points DESC , name
  LIMIT 0 , 30
) m
+1

, - :

SELECT IF(@currpoints := points, id, id)
+1

You can, of course, achieve what you need by using cursors, but there can be a performance hit.

0
source

Source: https://habr.com/ru/post/1703102/


All Articles