gpt4 book ai didi

mysql - 表上的 UNION 过程

转载 作者:行者123 更新时间:2023-11-29 06:57:30 24 4
gpt4 key购买 nike

如何将 stmtQuery 的所有结果联合到表 basia 和 Comments_11 ....等的一个结果示例结果

    DELIMITER $$
DROP PROCEDURE IF EXISTS SearchUserY $$
CREATE PROCEDURE `SearchUserY`(IN UserIdValue INT(11) )
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE tableName VARCHAR(50);
DECLARE stmtFields TEXT ;
DECLARE columnName VARCHAR(50) default 'UserId';

DECLARE cursor1 CURSOR FOR
SELECT table_name
FROM information_schema.COLUMNS
WHERE table_schema = 'comments'
AND column_name LIKE '%UserId';

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;


OPEN cursor1;
read_loop: LOOP
FETCH cursor1 INTO tableName;
IF done THEN
LEAVE read_loop;
END IF;

SET stmtFields = CONCAT('`',tableName,'`','.' , columnName ,'=', UserIdValue) ;


SET @stmtQuery=CONCAT(@sql,'SELECT Nick, Title, Content FROM ' ,'`',tableName,'`', ' WHERE ', stmtFields ) ;
select @stmtQuery;


END LOOP;

PREPARE stmt FROM @stmtQuery ;
EXECUTE stmt ;

DEALLOCATE PREPARE stmt;
CLOSE cursor1;
END

结果示例(选择@stmtQuery):

     SELECT Nick, Title, Content FROM `basia` WHERE `basia`.UserId=0
SELECT Nick, Title, Content FROM `Comments_11` WHERE `Comments_11`.UserId=0
... etc

我想从所有这些查询中得到一个结果,但知道我只得到一个结果

最佳答案

使用 CONCAT 函数在循环中生成查询,在它们之间添加 'UNION' 或 'UNION ALL' 子句,然后使用准备好的语句执行结果查询。

没有光标的解决方案:

SET @resultQuery = NULL;
SELECT
GROUP_CONCAT(
DISTINCT
CONCAT('SELECT Nick, Title, Content FROM ', table_name, ' WHERE UserId = ', UserIdValue)
SEPARATOR '\r\nUNION\r\n'
)
INTO
@resultQuery
FROM
information_schema.COLUMNS
WHERE
table_schema = 'comments' AND column_name LIKE '%UserId';

SELECT @resultQuery;

它会产生这样的结果:

SELECT Nick, Title, Content FROM table1 WHERE UserId = 10
UNION
SELECT Nick, Title, Content FROM table2 WHERE UserId = 10
UNION
SELECT Nick, Title, Content FROM table3 WHERE UserId = 10
UNION
SELECT Nick, Title, Content FROM table4 WHERE UserId = 10
...

如果需要,增加 group_concat_max_len 变量。它是 GROUP_CONCAT() 函数允许的最大结果长度,默认值 = 1024。

关于mysql - 表上的 UNION 过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11882594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com