表1
Groupname View
member table a
non member table b
teacher table c
表a
id key
1 A
2 B
3 C
表B
ID KEY
1 M
2 L
3 H
4 G
5 F
表C
ID KEY
1 Y
2 W
输出为
GROUPNAME KEY
member A
member B
member C
non member M
non member L
non member H
non member G
non member F
teacher Y
teacher W
答案 0 :(得分:1)
如果您想通过单个查询执行此操作,则最好对名称进行硬编码并使用union all
:
select 'member' as groupname, key
from a
union all
select 'non member' as groupname, key
from a
union all
select 'teacher' as groupname, key
from a;
我的意思是,您可以将子查询替换为:
select t1.groupname, key
from a join
table1 t1
on t1.view = 'a';
但是,将视图名称与groupname
硬编码似乎是任意的。
如果要更动态地执行此操作,则需要使用动态SQL。相反,我建议您更改数据结构,合并三个表并添加一个groupname
列。在表中存储表名和列名通常不是数据库设计的好方法。
答案 1 :(得分:0)
正如Gordon Linoff已经指出的那样:我认为您的数据库设计可以使用一些工作。如果您要编写动态SQL以创建与Gordon在其答案中创建的查询结构相同的查询结构,这将达到目的(只要每个视图都具有“键”变量,并且表是使用默认架构创建的) )。
declare @t1 table ([groupname] varchar(20), [view] varchar(20))
insert into @t1 values ('member','table a'),('non member','table 3'),('teacher','table 4')
declare @q varchar(max)='', @groupname varchar(20),@viewname varchar(20)
declare c cursor for select [groupname],[view] from @t1
open c
fetch next from c into @groupname, @viewname
while @@FETCH_STATUS=0
begin
set @q=@q+'select '''+@groupname+''' as Groupname, '+QUOTENAME(@viewname)+'.[key] from '+QUOTENAME(@viewname)+'{$crlf}union all{$crlf}'
fetch next from c into @groupname, @viewname
end
close c
deallocate c
set @q=replace(left(@q,len(@q)-23),'{$crlf}',CHAR(10))
print @q
exec (@q)