0

How can I create a Table based on SELECT statement with variable? I mean something like (simplified example):

    SET @tmp = 0; 

    CREATE TABLE test AS

    SELECT
        (@tmp:=@tmp + 1) test,
        ...
    FROM x

I use MySQL 5.7.

3
  • 1
    i have a feeling this is a workaround as it is not possible to generate row_number/sequence numbers in a MySQL view with user variables? ... Otherwise it's not clear to me why you want to do this.. Commented Sep 7, 2019 at 15:06
  • In general yes, but my code has also to handle some exceptions, so I couldn't just use this example. SQL code is working but I would like to create a table for simplification. Commented Sep 7, 2019 at 15:25
  • 1
    yes you indeed oversimplified as your example which you comment under Gordan's answer at first seight seams to be simulating ROW_NUMBER()/RANK() OVER(PARTITION BY ... ORDER BY ...) Commented Sep 7, 2019 at 15:28

1 Answer 1

2

Your code should work. You just need to give the column a name:

SET @tmp = 0; 

CREATE TABLE test AS
    SELECT (@tmp := @tmp + 1) as test_id
        ...
    FROM x;

You can combine this into a single statement:

CREATE TABLE test AS
    SELECT (@tmp := @tmp + 1) as test_id
        ...
    FROM x CROSS JOIN
         (SELECT @tmp := 0) params;

Here is a db<>fiddle

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

4 Comments

I missed alias only in example. I am getting Error Code: 1264. Out of range value for column '(null)' at row 1
@Kulis if you want to workaround the problem/error you can't use MySQL user variables in a view like i have explained in the comment under the question which feels like you are trying to do here.. Then using CREATE TEMPORARY TABLE test AS(..) instead might make more sense..
I probably too much simplified it. My original code has 4 variables and also nested SELECT statements. Here is more realistic version dbfiddle.uk/…
@Kulis . . . I would suggest that you ask a new question, with appropriate sample data, desired results, and the SQL Fiddle. This question has been answered.

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.