Home > other >  How can I store a sql query into a variable, not the result?
How can I store a sql query into a variable, not the result?

Time:11-26

Hello I am doing a script that needs to consult the results of another query Q1, this Q1 is used in a lot of other queries for example

select * from a,
where id in (Q1)

select * from b,
where id in (Q1)

select * from c,
where id in (Q1)

The problem is that Q1 can change a lot, so I want to store it in a SQL variable in order to avoid changing three times instead of one.

Is this possible?

How can I do this?

Thanks

CodePudding user response:

Here is a sample you can try to CREATE TEMPORARY TABLE Statement let your query be simply.

CREATE TEMPORARY TABLE `temp_Q`(
    `t_id` INT NOT NULL,
);

INSERT INTO temp_Q (t_id)
SELECT id
FROM Q;


select * from a,
where id in (SELECT t_id FROM temp_Q)

select * from b,
where id in (SELECT t_id FROM temp_Q)

select * from c,
where id in (SELECT t_id FROM temp_Q)
  • Related