在一个查询中,我有多行语句,如下图所示:
set @query = '';
select @query := concat(@query, ' union (select \'',bi.param2,'\' as tableName, ',bi.param3,' id, ', bi.param4, ' text from ', bi.param2,' where ',if(TRIM(bi.param5) is null, '1=1', bi.param5),')')
from itmanagement.BasicInfo bi where bi.param2 != '';
set @query := concat(SUBSTR(@query, 7, LENGTH(@query)));
set @wholeQuery := concat('select pe.*, bi.title label
, (case when bi.param1 = \'textfield\' then pe.ElemValue else od.text end) text
from PRC_PcdElements pe join BasicInfo bi on pe.ElemType = bi.InfoID join
(',@query,")
od on bi.param2 = od.tableName and pe.ElemValue = od.id
where bi.TypeID = 3 and pe.ProcedureID = '2';");
prepare stmt1 from @wholeQuery ;
execute stmt1 ;
此查询返回两列。一个用于第一个select语句,它只是一个赋值语句,以及exec语句的输出,它是所需的语句。
我想阻止第一个select语句将表打印到输出中,或者用更好的命令替换它(如果可用的话)。
答案 0 :(得分:1)
您可以使用SELECT ... INTO
语法尝试以下解决方案:
SET @query = '';
SELECT CONCAT(@query, ' UNION(SELECT \'',bi.param2,'\' AS tableName, ',bi.param3,' id, ', bi.param4, ' text FROM ', bi.param2,' WHERE ', IF(TRIM(bi.param5) IS NULL, '1=1', bi.param5),')') INTO @query
FROM itmanagement.BasicInfo bi WHERE bi.param2 != '' LIMIT 1;
SET @query := CONCAT(SUBSTR(@query, 7, LENGTH(@query)));
SET @wholeQuery := CONCAT('SELECT pe.*, bi.title label
, (CASE WHEN bi.param1 = \'textfield\' THEN pe.ElemValue ELSE od.text END) text
FROM PRC_PcdElements pe JOIN BasicInfo bi ON pe.ElemType = bi.InfoID JOIN
(',@query,")
od ON bi.param2 = od.tableName AND pe.ElemValue = od.id
WHERE bi.TypeID = 3 AND pe.ProcedureID = '2';");
PREPARE stmt1 FROM @wholeQuery;
EXECUTE stmt1;
您可以使用这样的语句(不带输出)设置@query
变量:
SELECT column_name INTO @query FROM table_name WHERE condition = true LIMIT 1
答案 1 :(得分:1)
您可以在其中创建一个临时的table
和insert
- select
所需的结果。此外,您可以在光标中选择查询,迭代它并构建所需的变量。