我很难解释这个问题,但也许一个例子有帮助...
我有两张桌子,a和b
a是一个空表,它有三列:
id name value
b是一个表,对于a和其他一些列具有相同的id,如下所示:
id obj_type obj_status language
-------------------------------------------------
1 product operational English
2 support operational French
3 product non_operational English
现在我想以这种方式将表b中的数据插入到a:
id name value
--------------------------------------
1 obj_type product
1 obj_status operational
1 language English
2 obj_type support
2 obj_status operational
2 language French
3 obj_type product
3 obj_status non_operational
3 language English
我想知道Postgres是否有办法做到这一点
答案 0 :(得分:0)
应该有效
INSERT INTO TableA
SELECT id,'obj_type' as Name, obj_type as Value FROM TableB UNION
SELECT id,'obj_status' as Name,obj_status as Value FROM TableB UNION
SELECT id,'languagee' as Name, language as Value FROM TableB
ORDER BY id
答案 1 :(得分:0)
SELECT id,
(SELECT Column_name FROM Information_schema.columns
WHERE Table_name ='tableB' AND ORDINAL_POSITION = 2) as Name, obj_type as Value FROM tableB UNION
SELECT id,
(SELECT Column_name FROM Information_schema.columns WHERE Table_name ='tableB' AND ORDINAL_POSITION = 3) as Name,obj_status as Value FROM tableB UNION
SELECT id,
(SELECT Column_name FROM Information_schema.columns WHERE Table_name ='tableB' AND ORDINAL_POSITION = 4) as Name, _language as Value FROM tableB
ORDER BY id,Name