[英]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.但突然它不起作用,因为
@result
作为一个字符串值处理,而不是作为数组处理。
Is it possible to pass variable as array?是否可以将变量作为数组传递? Any alternative solution (except subqueries) allowed.
允许任何替代解决方案(子查询除外)。
JOIN
between tables can be used in this case:在这种情况下可以使用表之间的
JOIN
:
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()
:您可以使用 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.