我不知道這是否可行。 我有Table1
以下字段。創建另一個MySQL的一個表列的行名稱
No
A
B
C
D
我要做個表1的table2's
列名列名(爲varchar(20)各中,所有空的)
A B C D
如果我table1中添加一行,表2列應當追加了。
有任何建議。
我不知道這是否可行。 我有Table1
以下字段。創建另一個MySQL的一個表列的行名稱
No
A
B
C
D
我要做個表1的table2's
列名列名(爲varchar(20)各中,所有空的)
A B C D
如果我table1中添加一行,表2列應當追加了。
有任何建議。
這裏有一些關於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;
希望有所幫助。
謝謝..這是一個很好的開始爲了我.. ! – Ank
不用擔心 - 我已經添加了一個編輯,包含了我在MySQL上工作的一個版本 - 希望能爲您解決這個問題。 – JohnLBevan
目前尚不清楚你正在嘗試做什麼。但是,如果你只是想從這些行中的數據成爲一個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
如果你想反其道而行,把列進行,然後你用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
你想使表有colu名字?或者選擇這些值作爲列名的數據? – Taryn
我想讓table2具有table1行的列名稱 – Ank