简体   繁体   English

插入案例陈述中

[英]Insert inside of a case statement

I have a table of data in which I have decided I want to change the way I save and extract data. 我有一个数据表,在该表中,我已经决定要更改保存和提取数据的方式。 It was a poor design on my part and now I need to fix it without going through every row manually. 就我而言,这是一个糟糕的设计,现在我需要修复它,而无需手动检查每一行。 I want to change the primary keys from ItemID and VendorID to ItemID and Function. 我想将主键从ItemID和VendorID更改为ItemID和Function。 I want a separate record for each function+id rather than a combined record if the vendor id is the same for both functions. 如果两个功能的供应商ID相同,我希望为每个功能+ ID单独记录,而不是组合记录。 I will be eliminating the use of the other_functions column. 我将消除对other_functions列的使用。

Basically my table looks something like this: 基本上我的桌子看起来像这样:

ItemID(PK)| VendorID(PK) |   Function   |   other_functions
_______________________________________________________
    1     |    23        |    cooking   |     
    1     |    36        |    cleaning  |
    2     |    45        |    cooking   |   cleaning

After I update the PK's, How do I go through the table, and for each record where other_functions = 'cleaning', insert a new row to make it look more like this: 更新PK后,如何浏览表格,并为other_functions ='cleaning'的每条记录插入新的一行,使其看起来像这样:

ItemID(PK)| VendorID     | Function(PK)   
______________________________________
    1     |    23        |    cooking     
    1     |    36        |    cleaning 
    2     |    45        |    cooking
    2     |    45        |    cleaning

I am using PostgreSQL. 我正在使用PostgreSQL。 It seems like it should be a simple solution but haven't been able to find the answer I am looking for. 看来这应该是一个简单的解决方案,但找不到我要找的答案。 Can this be done with just an insert + case statement? 可以仅使用insert + case语句来完成此操作吗?

Can this be done with just an insert + case statement? 可以仅使用insert + case语句来完成此操作吗?

CASE would make the value conditional - in your case you want to make the insert itself conditional. CASE会将值设置为条件-在您的情况下,您希望将插入本身设置为条件。 A better method would just be to insert records that have a other_functions value: 更好的方法是插入具有other_functions值的记录:

INSERT INTO {table}
(ItemID, VendorId, Function)
(
SELECT ItemID, VendorId, other_functions
FROM {table}
WHERE other_functions IS NOT NULL
)

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

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