Oracle sql MERGE INTO带有一个where子句

时间:2017-06-19 15:43:44

标签: sql oracle where-clause sql-merge

我有以下SQL代码(这是我到目前为止已经有多少):

var bookRecords = from c in doc.Descendants("Book")
                   select new { bookCardNo = c.Element("CardNo").Value };

var LibraryRecords = from d in doc.Descendants("Library")
                     select new { libCardNo = d.Element("CardNo").Value,
                                  rackno = d.Element("RackNo").Value  };

var groupedRecords = 
    from br in bookRecords
    join lr in LibraryRecords 
    on br.bookCardNo equals lr.libCardNo
    select lr.rackno;

以下是VIEW_1的定义:

 MERGE INTO SCHEMA1.TABLE_1 table1 USING
    (
     SELECT DISTINCT table2.column1, 
            view1.column2
     FROM SCHEMA2.TABLE_2 table2
     LEFT JOIN SCHEMA2.VIEW_1 view1
     ON table2.column2 = view1.column3

    ) t2 ON (table1.column3 = t2.column1 )

    WHEN MATCHED THEN
      UPDATE
      SET table1.column4 = t2.column2;

但我收到以下错误消息:

    CREATE VIEW SCHEMA_2.VIEW_1
AS (SELECT 
SCHEMA_2.TABLE_1.COLUMN_1, 
SCHEMA_2.TABLE_2.COLUMN_1,
SCHEMA_2.TABLE_2.COLUMN_2,
SCHEMA_2.TABLE_2.COLUMN_3,
SCHEMA_2.TABLE_5.COLUMN_1, 
SCHEMA_2.TABLE_6.COLUMN_1, 
SCHEMA_2.TABLE_6.COLUMN_2,
SCHEMA_2.TABLE_6.COLUMN_3,
SCHEMA_2.TABLE_6.COLUMN_4, 
SCHEMA_2.TABLE_7.COLUMN_1, 
SCHEMA_2.TABLE_7.COLUMN_2, 
SCHEMA_2.TABLE_8.COLUMN_1 
FROM SCHEMA_2.TABLE_1
INNER JOIN SCHEMA_2.TABLE_2
ON SCHEMA_2.TABLE_1.COLUMN_1 = SCHEMA_2.TABLE_2.COLUMN_2 
INNER JOIN SCHEMA_2.TABLE_5
ON SCHEMA_2.TABLE_1.COLUMN_4 = SCHEMA_2.TABLE_5.COLUMN_3
LEFT OUTER JOIN SCHEMA_2.TABLE_6
ON SCHEMA_2.TABLE_2.COLUMN_2 = SCHEMA_2.TABLE_6.COLUMN_4
LEFT OUTER JOIN SCHEMA_2.TABLE_7
ON SCHEMA_2.TABLE_2.COLUMN_1 = SCHEMA_2.TABLE_8.COLUMN_5
);

导致错误的原因是什么?在哪里更改代码以使其工作?

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

对于此示例,您的问题肯定在USING子查询中。此查询会生成多个table2.column1

的值
SELECT DISTINCT table2.column1, 
        view1.column2
 FROM SCHEMA2.TABLE_2 table2
 LEFT JOIN SCHEMA2.VIEW_1 view1
 ON table2.column2 = view1.column3

因此ON子句将多次匹配table1中的相同行:

ON (table1.column3 = t2.column1 )

Oracle无法确定在UPDATE中应使用t2.column2的哪个值,因此它会抛出ORA-30926

在子查询中使用distinct无济于事,因为这会给出所有列的排列。您需要编写一个子查询,该子查询将在所有行中生成t2.column1的唯一值,或者添加另一个标识列以生成可以加入table1的唯一键。

答案 1 :(得分:1)

根据我的经验,这个错误不仅在USING子句为MATCH表中的一行返回多行时返回,而且还经常在它不能确定时只返回一行将被返回(即使没有返回多行的实际情况)。为了强制解析器在这种情况下接受查询,我通常会在MATCH..ON列上使用GROUP BY。

MERGE INTO SCHEMA1.TABLE_1 table1 USING
(
 SELECT table2.column1, 
        MAX(view1.column2) as column2
 FROM SCHEMA2.TABLE_2 table2
 LEFT JOIN SCHEMA2.VIEW_1 view1
 ON table2.column2 = view1.column3
 GROUP BY table2.column1
) t2 ON (table1.column3 = t2.column1 )

WHEN MATCHED THEN
  UPDATE
  SET table1.column4 = t2.column2;