根据表B中的记录更新表A中的记录

时间:2011-04-03 19:53:31

标签: sql sql-update projection

我必须编写一个语句,用合成生成的值填充表(customers)。有一个附加约束,我应该只用特殊属性填充那些属性(列)(即正式对它们进行投影,然后专门对它们进行操作)。这些属性存储在第二个表attributes

我的初稿包括以下两个陈述:

-- Get the attributes (columns) we are interested in only
SELECT attributeID from attributes
WHERE tableID = 'customers'

-- Iterate over each row of customers, filling only those attributes (columns)
-- obtained by the above SELECT statement
UPDATE customers
   SET (use the records from above select statement...)

现在我的问题是如何将它们组合在一起。我知道有可能在SET子句中附加一个WHERE子句,但这会根据需要选择行而不是列。我还读到了PIVOT,但到目前为止只在一张表内,而不是两张,就像这里的情况一样。我会非常感谢任何提示,因为我不知道如何做到这一点。

2 个答案:

答案 0 :(得分:4)

你不是在寻找吗? SQL Update Multiple Fields FROM via a SELECT Statement

UPDATE
    Table
SET
    Table.col1 = other_table.col1,
    Table.col2 = other_table.col2
FROM
    Table
INNER JOIN
    other_table
ON
    Table.id = other_table.id

答案 1 :(得分:2)

标准SQL-92需要标量子查询:

UPDATE customers
   SET attributeID = (
                      SELECT A1.attributeID 
                        FROM attributes AS A1
                       WHERE A1.tableID = 'customers'
                     );

然而,UPDATE customers...WHERE A1.tableID = 'customers'“闻起来像是你可能将数据与元数据混合在一起。

相关问题