Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign query results to MySQL variable

I'm querying a big mysql database with only read privileges, and I'd like to set some slow query results to a variable, 'foo', so I can use them again in other queries.

Basically, I want to have a variable for a cumbersome subquery, so I can reuse it without having the cost of running it every time I want to use it.

when I enter:

set @foo := (select *
            from table1 join table2 
            where bar = 0 
            group by id);

I get: ERROR 1241 (21000): Operand should contain 1 column(s) and if I restrict to 1 column, ERROR 1242 (21000): Subquery returns more than 1 row

Is there a way to store an array or a table in a variable? I don't have privileges to create temporary tables.

like image 639
5un5 Avatar asked Dec 06 '12 05:12

5un5


People also ask

What does := mean in MySQL?

Description. := Assign a value. = Assign a value (as part of a SET statement, or as part of the SET clause in an UPDATE statement)

Can we declare variable in MySQL query?

You can declare a variable using @anyVariablename which is a session variable. To create a session variable, you need to use SET command.


1 Answers

it should be @ when you are doing in MySQL.

set @foo := (select *
            from table1 join table2 
            where bar = 0 
            group by id);
like image 112
John Woo Avatar answered Sep 25 '22 15:09

John Woo