简体   繁体   English

根据值列表向 SQL 表添加行

[英]Add rows to SQL table based on a list of values

So I have a table like this and an attribute list - ( 'attr1' , 'attr2' , 'attr3' ).所以我有一个这样的表和一个属性列表 - ( 'attr1' , 'attr2' , 'attr3' )。

id | attr_name | attr_value
----------------------------
 1 |   attr1   |  val1 
 1 |   attr2   |  val2
 1 |   attr3   |  val3 
 2 |   attr1   |  val1
 2 |   attr2   |  val4

I want to make a query where this table can be "expanded" to be the following and then make a query using it.我想进行一个查询,该表可以“扩展”为以下内容,然后使用它进行查询。

id | attr_name | attr_value
----------------------------
 1 |   attr1   |  val1 
 1 |   attr2   |  val2
 1 |   attr3   |  val3 
 2 |   attr1   |  val1
 2 |   attr2   |  val4
 2 |   attr3   |  null

The attribute list is given to me and dynamic.属性列表是动态给我的。

Cross join the IDs and the attribute names and then left join the table to get the attribute values or NULL if no match was found.交叉连接 ID 和属性名称,然后左连接表以获取属性值,如果未找到匹配项,则为NULL

SELECT x1.id,
       x2.attr_name,
       t2.attr_value
       FROM (SELECT DISTINCT
                    t1.id
                    FROM elbat t1) x1
            CROSS JOIN (VALUES ('attr1'),
                               ('attr2'),
                               ('attr3')) x2 (attr_name)
            LEFT JOIN elbat t2
                      ON t2.id = x1.id
                         AND t2.attr_name = x2.attr_name
       ORDER BY x1.id,
                x2.attr_name;                     
WITH 
ids AS ( SELECT DISTINCT id
         FROM sourcetable ),
attrs AS ( SELECT DISTINCT attr_name
           FROM sourcetable )
INSERT INTO sourcetable (id, attr_name)
SELECT id, attr_name
FROM ids, attrs
EXCEPT
SELECT id, attr_name
FROM sourcetable

sorry if this seems obvious, but did you try对不起,如果这看起来很明显,但你有没有尝试

INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')

? ?

Then when you query your table it should contain the value然后当你查询你的表时,它应该包含值

Edit: also you may want to have a unique key编辑:你也可能想要一个唯一的键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM