[英]How to select from dynamic table name
I have tables like 我有桌子
changes201101
changes201102
changes201103
...
changes201201
And table whichchanges
which contain rows Year and MONTH 和包含whichchanges
和月的行的表
How I can select * from changes from whichchanges
? 我怎样才能从改变选择* whichchanges
?
I type this query 我输入这个查询
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 - You have an error in your SQL syntax; #1064 - 您的SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT CONCAT('changes',year,month) FROM changes)' at line 1 查看与您的MySQL服务器版本对应的手册,以便在第1行的'SELECT CONCAT('更改',年,月)FROM更改'附近使用正确的语法
You open 1 (
and close 2 )
. 你打开1 (
并关闭2 )
。 Remove the last: 删除最后一个:
SELECT CONCAT('changes',year,month) FROM changes
the second statement should probably be 第二个陈述应该是
SET @x := SELECT * FROM (@b) as b;
That works, but not sure if that is what you want: 这有效,但不确定这是否是你想要的:
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;
If I understood you right you are looking for that single query: 如果我理解你正确,你正在寻找那个单一的查询:
select * from changes
where change_column in (select distinct concat(`year`, `month`) from whichchanges)
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.