如何将 select 查询设置为变量并在 mysql 中的另一个 select 查询中使用它

How can set a select query to a variable and use it in another select query in mysql

我有 10 多个 select 查询。在我需要使用通用子查询的所有查询中。所以为了可重用性,我想到了将子查询放在一个变量中,然后在其他 select 查询中使用它。 以下是我正在尝试但无法正常工作的示例代码。

declare querySelect varchar(1000);
set querySelect="SELECT Id from orgs where orgType =5";

select * from organisation where Id in (select querySelect);

此处的一个选项是创建视图:

CREATE VIEW orgView AS
SELECT Id FROM orgs WHERE orgType = 5;

然后 select 从这个视图在你的后续查询中,例如

SELECT * FROM organisation WHERE Id IN (SELECT Id FROM orgView);

您可以使用prepare statement

set @querySelect="SELECT Id from orgs where orgType =5";
SET @sql = CONCAT("select * from organisation where Id in ( ",@querySelect," )");
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;