2012-10-12 90 views
1

我不知道这是否可行。 我有Table1以下字段。创建另一个MySQL的一个表列的行名称

No 

A 
B 
C 
D 

我要做个表1的table2's列名列名(为varchar(20)各中,所有空的)

A B C D 

如果我table1中添加一行,表2列应当追加了。

有任何建议。

+1

你想使表有colu名字?或者选择这些值作为列名的数据? – Taryn

+0

我想让table2具有table1行的列名称 – Ank

回答

1

这里有一些关于T-SQL(SQL Server)中的一些伪解决方案的信息,其中一些可能转移到MySQL:http://sqlserveradvisor.blogspot.co.uk/2009/03/sql-server-convert-rows-to-columns.html 但是没有简单的方法。

我能想出(又在T-SQL)最好是这样的动态SQL解决方案:

declare @tempTable table (ColumnName nvarchar(10)) 
    declare @sql nvarchar(max) 
    insert @tempTable 
    select 'Col1' 
    union select 'Col2' 
    union select 'Col3' 
    select @sql = isnull(@sql+ ',','') + '1 ' + quotename(ColumnName) 
    from @tempTable 
    set @sql = 'select ' + @sql 
    exec(@sql) 

- 编辑 -

我已经成功地在尝试了一个脚本MySQL(通过在线主机在这里:http://headfirstlabs.com/sql_hands_on/hf01.htm)。下面的代码适用于演示数据库,所以应该在你的桌面上工作。由于列数包含列号,所以我稍微过分了一些,因为我有点困惑,但希望它有帮助,所以我现在就把它留下了。

set @test:='select'; 
set @i:=1; 
select @test:=concat(@test, ' ',case when @i>1 then ',' else '' end, ' ''Col', @i, ''' as ', last_name) , @i:[email protected]+1 from my_contacts; 
select @test; 
PREPARE stmt1 FROM @test; 
execute stmt1; 

(简化版本的MySQL)

set @sql:='select'; 
select @sql:=concat(@sql, case when @sql>'select' then ', ' else ' ' end, '0 as ', last_name) from my_contacts; 
select @sql; 
PREPARE stmt1 FROM @sql; 
execute stmt1; 

希望有所帮助。

+0

谢谢..这是一个很好的开始为了我.. ! – Ank

+0

不用担心 - 我已经添加了一个编辑,包含了我在MySQL上工作的一个版本 - 希望能为您解决这个问题。 – JohnLBevan

0

这是不可能的,只使用查询,你需要在服务器端语言工作来实现这一点。

+0

ya .. true ..我想知道如果一个查询可以做到这一点..会节省我一些时间.. :) – Ank

1

目前尚不清楚你正在尝试做什么。但是,如果你只是想从这些行中的数据成为一个SELECT行,那么你可以做这样的事情:

select 
    max(case when no = 'A' then col end) as A, 
    max(case when no = 'B' then col end) as B, 
    max(case when no = 'C' then col end) as C, 
    max(case when no = 'D' then col end) as D 
from table1 

SQL Fiddle With Demo

如果你想反其道而行,把列进行,然后你用UNION ALL

select col1 No 
from table1 
union all 
select col2 No 
from table1 
union all 
select col3 No 
from table1 
union all 
select col4 No 
from table1 

SQL Fiddle With Demo

+0

哦,不!对不起如果我不清楚。我希望tableB的列名是tableA的行名。 – Ank

+0

@Ankur查看我的编辑 – Taryn

+0

在将来向table1添加一行时会发生什么 – Ank

相关问题