简体   繁体   中英

How to use result from SELECT query in another one

I need to use selected rows in another query without selecting them again as subquery. Would be perfect if here possible to store them as variable.

What I mean:

/* First query: only one column returns (always), but multiple records, trying to store them as string */
SET @result := (SELECT GROUP_CONCAT(target_field SEPARATOR ',')
FROM table_one
WHERE condition;

/* Second query: need to pass saved array into IN() condition */
SELECT *
FROM table_two
WHERE id IN(@result);

But suddenly it won't work because @result processed as one string value, not as array.

Is it possible to pass variable as array? Any alternative solution (except subqueries) allowed.

you could just use a subquery in your where condition. This should be ok for mySql

SELECT *
FROM table_two
WHERE id IN(SELECT id from table_one where condition_one);

JOIN between tables can be used in this case:

SELECT *
FROM table_two
JOIN table_one ON table_two.id = table_one.target_field
WHERE table_one condition;

You can use the function FIND_IN_SET() :

SELECT *
FROM table_two
WHERE FIND_IN_SET(id, @result);

If subquery it is not allowed you can use Store Procedure:

Try:

DELIMITER //
CREATE PROCEDURE my_procedure()
BEGIN
SET @result = "SELECT GROUP_CONCAT(target_field SEPARATOR ',') FROM table_one WHERE condition";
SET @finalqry = CONCAT("SELECT * FROM table_two WHERE id IN (", @result, ") ");
PREPARE stmt FROM @finalqry;
EXECUTE stmt;
END//
DELIMITER ;

Call it:

call my_procedure();

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