如何在另一个查询中使用 SELECT 查询的结果

How to use result from SELECT query in another one

我需要在另一个查询中使用选定的行,而无需再次选择它们作为子查询。如果可以将它们存储为变量就完美了。

我的意思是:

/* 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);

但突然间它不起作用,因为 @result 处理为 一个 字符串值,而不是数组。

是否可以将变量作为数组传递?允许任何替代解决方案(子查询除外)。

您可以在 where 条件中使用子查询。这对于 mySql

应该没问题
SELECT *
FROM table_two
WHERE id IN(SELECT id from table_one where condition_one);

JOIN表间可以用在这种情况下:

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

您可以使用函数 FIND_IN_SET():

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