如何从动态表名中选择

时间:2012-05-07 10:23:45

标签: mysql select dynamic

我有像

这样的表格
changes201101
changes201102
changes201103
...
changes201201

和表 whichchanges包含行Year和MONTH

如何从whichchanges的更改中选择*?

我输入此查询

SET @b := SELECT CONCAT('changes',year,month) FROM whichchanges;
((((@b should contain now multiple rows of changesYearMonth)))))
SET @x := SELECT * FROM @b;
Prepare stmt FROM @b;
Prepare stmt FROM @x;
Execute stmt;
  

#1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在第1行的'SELECT CONCAT('更改',年,月)FROM更改'附近使用正确的语法

1 个答案:

答案 0 :(得分:7)

您打开1 (并关闭2 )。删除最后一个:

SELECT CONCAT('changes',year,month) FROM changes

修改

第二个陈述应该是

SET @x := SELECT * FROM (@b) as b;

这有效,但不确定这是否是你想要的:

SET @b := 'SELECT CONCAT(''changes'',`year`,`month`) FROM whichchanges';
SET @x := 'SELECT * FROM (SELECT CONCAT(''changes'',`year`,`month`) FROM whichchanges) as b';
Prepare stmt FROM @b;
Prepare stmt FROM @x;
Execute stmt;

EDIT2

如果我理解你正确,你正在寻找那个单一的查询:

select * from changes
where change_column in (select distinct concat(`year`, `month`) from whichchanges)

EDIT3

select @b := group_concat(concat(' select * from changes', `year`, `month`, ' union ') separator ' ') as w from whichchanges;
set @b := left(@b, length(@b) - 6);

Prepare stmt FROM @b;
Execute stmt;

SQLFiddle example