0

我如何浏览数据库中的所有表,因为我想找到特定数量的 UserId 其中 X - 它是一个数字 UserId 示例 X = 2 所以我必须找到 UserId = 2

我使用 MySQL,我想创建过程

我的数据库架构:

Something ( ... ) --> without UserId
Something1 (... , UserId,...)
Something2 (... , UserId,...)
Something3 (... , UserId,...)
Cat
Cat1
Cat2
Cat3
Cat4
etc....

没有数字的表格可能我们称为 PARENT 和带有数字示例的表格 (Cat1, Cat2... Cat3..) 我们称为 CHILDREN>

当我们在一张表中获得 20000 条记录时,将动态创建 CHILDREN

我想要调用程序示例:CALL SearchUser(X) where X - number of UserId

如果有人有脚本,我将不胜感激,或者如果有人也帮助我

4

1 回答 1

0

不确定这是否有效。请试一试。数据库名称在这里是硬编码的WHERE TABLE_SCHEMA IN ('test')

## Procedure for search in all fields of all databases
DELIMITER $$
#Script to loop through all tables using Information_Schema
DROP PROCEDURE IF EXISTS get_table $$
CREATE PROCEDURE get_table(in_search varchar(50),in_column_name varchar(50))
READS SQL DATA
BEGIN
DECLARE trunc_cmd VARCHAR(50);
DECLARE search_string VARCHAR(250);
DECLARE db,tbl,clmn CHAR(50);
DECLARE done INT DEFAULT 0;
DECLARE COUNTER INT;
DECLARE table_cur CURSOR FOR
SELECT concat('SELECT COUNT(*) INTO @CNT_VALUE FROM `',table_schema,'`.`',table_name,'` WHERE `', in_column_name,'` = "',in_search,'"') ,table_schema,table_name,column_name FROM information_schema.COLUMNS WHERE TABLE_SCHEMA IN ('test') and column_name=in_column_name ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
#Truncating table for refill the data for new search.
PREPARE trunc_cmd FROM "TRUNCATE TABLE temp_details;";
EXECUTE trunc_cmd ; 
OPEN table_cur;
table_loop:LOOP
FETCH table_cur INTO search_string,db,tbl,clmn;
#Executing the search
SET @search_string = search_string;
SELECT  search_string;
PREPARE search_string FROM @search_string;
EXECUTE search_string;
SET COUNTER = @CNT_VALUE;
SELECT COUNTER;
IF COUNTER>0 THEN
# Inserting required results from search to table
INSERT INTO temp_details VALUES(db,tbl,clmn);
END IF;
IF done=1 THEN
LEAVE table_loop;
END IF;
END LOOP;
CLOSE table_cur;

END $$
DELIMITER ;

临时表结构:

CREATE TABLE `temp_details` ( 
`t_schema` varchar(45) NOT NULL,
`t_table` varchar(45) NOT NULL,
`t_field` varchar(45) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

调用程序:

call get_table('2','userID');
select * from temp_details;
于 2012-07-26T09:03:12.937 回答