从带有参数的未知表中选择

时间:2018-10-08 11:25:26

标签: mysql sql stored-procedures parameters stored-functions

我想使用参数从多个表中选择(联合)行

我有两列的表w

table_name引用数据库中的其他表,condition是应添加到查询中的'where'。

table_name | condition 
---------------------
x          |  y=2
x          |  r=3
t          |  y=2

查询应类似于:

select * from x where y=2
union
select * from x where r=3
union
select * from t where y=2

当然工会的数目是未知的。

应该是存储过程吗?光标?

2 个答案:

答案 0 :(得分:0)

完成此任务的一种方法。最初的答案是SQL Server语法。此编辑具有MySQL语法。确保不能同时访问您的临时表。例如。在MySQL中,临时表对于连接是唯一的。还添加您的错误检查。在MySQL中,根据您的需要设置适当的varchar大小。我将1024全部用于测试目的。

MySQL语法

CREATE table test (
    id int,
    table_name varchar(1024),
    where_c varchar(1024)
);

INSERT into test(id, table_name, where_c) values
(1,'x','y=2'),
(2,'x','r=3'),
(3,'t','y=2');

DROP PROCEDURE IF EXISTS generate_sql;

DELIMITER //
CREATE PROCEDURE generate_sql()
BEGIN
DECLARE v_table_name VARCHAR(1024);
DECLARE v_where_c VARCHAR(1024);
DECLARE table_id INT;
DECLARE counter INT;
DECLARE v_SQL varchar(1024);

CREATE TEMPORARY table test_copy
SELECT * FROM test;

SET v_SQL = '';

SET counter = (SELECT COUNT(1) FROM test_copy);
WHILE counter > 0 DO
    SELECT id, table_name, where_c
    INTO table_id, v_table_name, v_where_c
    FROM test_copy LIMIT 1;

    SET v_SQL = CONCAT(v_SQL, 'SELECT * FROM ', v_table_name, ' WHERE ', v_where_c);

    DELETE FROM test_copy WHERE id=table_id;
    SET counter = (SELECT COUNT(1) FROM test_copy);

    IF counter > 0 THEN
        SET v_SQL = CONCAT(v_SQL,' UNION ');
    ELSE
        SET v_SQL = v_SQL;
    END IF;
END WHILE;

DROP table test_copy;

SELECT v_SQL;
END //
DELIMITER ;

call generate_sql()

SQL Server语法

CREATE table test (
    id int,
    table_name varchar(MAX),
    condition varchar(MAX)
);

INSERT into test(id, table_name, condition) values
(1,'x','y=2'),
(2,'x','r=3'),
(3,'t','y=2');

SELECT * INTO #temp FROM test;

DECLARE @SQL varchar(MAX);
SET @SQL='';

while exists (select * from #temp)
begin

    DECLARE @table_name varchar(MAX);
    DECLARE @condition varchar(MAX);
    DECLARE @table_id int;

    SELECT top 1 @table_id=id, @table_name=table_name, @condition=condition FROM #temp;

    SET @SQL += 'SELECT * FROM ' + @table_name + ' WHERE ' + @condition;

    delete #temp where id = @table_id;

    if exists (select * from #temp) SET @SQL += ' UNION ';
end

SELECT @SQL;
drop table #temp;

答案 1 :(得分:0)

假设表Stringx具有相同的定义,并且您想通过使用UNION而不是UNION ALL来忽略重复的结果,则应该可以进行以下操作:

t

(由于您对表SET @sql = ''; SELECT GROUP_CONCAT( CONCAT('SELECT * FROM `', `table_name`, '` WHERE ', `condition`) SEPARATOR ' UNION ') INTO @sql FROM w; SET @sql = CONCAT('SELECT * FROM ( ', @sql, ' ) a;'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; 有两个不同的定义,所以我对您的问题进行了稍微的编辑)