skip to Main Content

I want to use SELECT clause inside the VALUES like this: The point is to get a random value from another table

 VALUES (SELECT x FROM seq_data ORDER BY RAND() LIMIT 1;, ...)

Yet this returns an error,

Otherwise I have to set variable and the execution becomes so slow like that

 SELECT @id := x FROM seq_data ORDER BY RAND() LIMIT 1;
 VALUES(@id, ... )

What is the solution around this?

2

Answers


  1. If you use a subquery in place of a scalar value, you must put it in parentheses:

    INSERT ...
    VALUES ((SELECT x FROM seq_data ORDER BY RAND() LIMIT 1), ...);
            ^                                              ^
    

    Also: don’t use a semicolon (;) inside a subquery. Only use a semicolon at the end of the whole statement.

    Login or Signup to reply.
  2. Use INSERT .. SELECT:

    INSERT INTO table1 (col_1, col_2, ..., col_N)
    SELECT x, 'literal 2', ..., 'literal N'
    FROM seq_data  
    ORDER BY RAND() LIMIT 1;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search