首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用IN-运算符作为变量使用MySQL查询的结果。

使用IN-运算符作为变量使用MySQL查询的结果。
EN

Stack Overflow用户
提问于 2022-06-20 12:06:40
回答 1查看 60关注 0票数 0

寻找一种返回可以在IN-operator中使用的变量的方法。

我当前的结果返回:1,2,3,但我想变量应该更像这样:'1','2','3'才能使用它。

这个是可能的吗?

或者我应该尝试一些其他的东西,比如爆炸,保存查询,.

代码语言:javascript
复制
-- init vars
SET @export_date = '2022-06-20'; 
SET @order_ids = ''; 

-- Tasks on given day
SELECT * FROM tasks WHERE task_execution_date = @export_date;

-- method 1
SET @order_ids = (SELECT GROUP_CONCAT(DISTINCT task_order SEPARATOR ',' )  FROM tasks WHERE task_execution_date = @export_date); 
SELECT @order_ids; -- "1,2,3"

-- method 2
SET @order_ids = (SELECT GROUP_CONCAT(DISTINCT '' + cast( task_order  AS CHAR(50)) +'' )  FROM tasks WHERE task_execution_date = @export_date); 
SELECT @order_ids; -- "1,2,3"

-- method 3
SET @order_ids =  (SELECT GROUP_CONCAT( DISTINCT + '\'' + CAST(task_order AS CHAR (100)) + '\'') FROM tasks WHERE task_execution_date = @export_date); 
SELECT @order_ids; -- "1,2,3"

-- Orders by tasks 
 SELECT * from orders WHERE ordr_id IN (@order_ids);     -- returns only one result
 -- SELECT * from orders WHERE ordr_id IN @order_ids;    -- error
 SELECT * from orders WHERE ordr_id IN ('1', '2', '3');  -- works
 SELECT * from orders WHERE ordr_id IN (SELECT DISTINCT task_order FROM tasks WHERE task_execution_date = @export_date); -- works


-- Also needed: 
-- goods by orders
-- good_adrs by goods
EN

回答 1

Stack Overflow用户

发布于 2022-06-20 17:23:35

如果您真的,真的,我的意思是真正知道这些变量不可能是邪恶的,那么您可以构建和执行原始查询:

代码语言:javascript
复制
SET @export_date = '2022-06-20';
SET @order_ids = (SELECT GROUP_CONCAT(DISTINCT task_order SEPARATOR ',' )  FROM tasks WHERE task_execution_date = @export_date); 
SET @query = CONCAT('SELECT * from orders WHERE ordr_id IN (', @order_ids, ');');
PREPARE stmt FROM @query;
EXECUTE stmt;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72686745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档