寻找一种返回可以在IN-operator中使用的变量的方法。
我当前的结果返回:1,2,3,但我想变量应该更像这样:'1','2','3'才能使用它。
这个是可能的吗?
或者我应该尝试一些其他的东西,比如爆炸,保存查询,.
-- 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发布于 2022-06-20 17:23:35
如果您真的,真的,我的意思是真正知道这些变量不可能是邪恶的,那么您可以构建和执行原始查询:
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;https://stackoverflow.com/questions/72686745
复制相似问题