简体   繁体   中英

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.

it should be @ when you are doing in MySQL .

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

You can also try this:

You cant store full table in any variable but you can store column data in any variable using below query.

SELECT GROUP_CONCAT(col1 SEPARATOR '~~~'), GROUP_CONCAT(col2 SEPARATOR '~~~'), ... INTO @foo, @foo2, ...
FROM table1 JOIN table2 
WHERE bar = 0 
GROUP BY id;

or

select col1, col2, ... into @foo, @foo2, ...
from table1 join table2 
where bar = 0 
group by id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM