更新列的值,以便与其他列形成唯一约束

时间:2013-04-12 17:13:08

标签: sql oracle sql-server-2008

我的表A包含列a1,a2,a3,表B包含列b1,b2。 Currenly a2列(表A)包含所有空值,我想通过b2(表B)中的随机值更新a2值。但是当更新a2时,我需要检查它与列a1的唯一形式。意味着它应该是(a1,a2)应该是唯一的。实现这一目标的最佳方式是什么。我正在使用sql 2008.但我需要确保它也能运行oracle。

我试过以下选择随机发生的事情。

update A set a2 = (SELECT TOP 1 b2 FROM B ORDER BY newid())
where a2 is null
[but also need to form unique (a1,a2)]

2 个答案:

答案 0 :(得分:1)

注意:在澄清表格b的行数少于表格a后,我更改了此答案。

可以使用MERGE完成此操作。

首先,假设表格a包含以下a1值的行:1, 1, 1, 1, 2, 2, 2, 2, 7, 7, 10, 10, 10, 10, 12, 12, 13, 13, 13, 13, 15, 15

接下来,假设表格b包含以下b2值的行:102, 103, 104, 105, 106, 107, 108

每个a1值都可以使用此查询轮流与b2值配对:

SELECT * FROM
 (SELECT a1, ROW_NUMBER() OVER (PARTITION BY a1 ORDER BY NULL) AS RowA
    FROM a) TableA
INNER JOIN
 (SELECT b2, ROW_NUMBER() OVER (Order by b2) AS RowB
    FROM b) TableB
ON Tablea.RowA = TableB.RowB

 A1 ROWA  B2 ROWB
--- ---- --- ----
  1    1 102    1 <-- first a1=1 goes with b2=102
  1    2 103    2 <-- second a1=1 goes with b2=103
  1    3 104    3 <-- third a1=1 goes with b2=104
  1    4 105    4 <-- fourth a1=1 goes with b2=105
  2    1 102    1 <-- start again: first a1=2 goes with b2=102
  2    2 103    2 <-- and so on...
  2    3 104    3
  2    4 105    4
  7    1 102    1
  7    2 103    2
 10    1 102    1
 10    2 103    2
 10    3 104    3
 10    4 105    4
 12    1 102    1
 12    2 103    2
 13    1 102    1
 13    2 103    2
 13    3 104    3
 13    4 105    4
 15    1 102    1
 15    2 103    2

这对于合并来说还不够,因为它不能唯一地标识表a行,但ROWID可以处理这些行。这是完整的查询:

MERGE INTO a
USING (
  SELECT * FROM
   (SELECT
        a.ROWID as ID,
        a1,
        ROW_NUMBER() OVER (PARTITION BY a1 ORDER BY a2) AS RowA
      FROM a) TableA
  INNER JOIN
   (SELECT b2, ROW_NUMBER() OVER (Order by b2) AS RowB
      FROM b) TableB
  ON Tablea.RowA = TableB.RowB) AtoB
ON (a.ROWID = AtoB.ID)
WHEN MATCHED THEN UPDATE SET a.a2 = AtoB.b2

以下是更新后表a的内容:

SELECT a1, a2 FROM a ORDER BY a1, a2;

 A1   A2
--- ----
  1  102
  1  103
  1  104
  1  105
  2  102
  2  103
  2  104
  2  105
  7  102
  7  103
 10  102
 10  103
 10  104
 10  105
 12  102
 12  103
 13  102
 13  103
 13  104
 13  105
 15  102
 15  103

答案 1 :(得分:0)

您可以使用此类查询

    CREATE TABLE A(a1 INT ,a2 INT, a3 int)

    CREATE TABLE B(b1 INT ,b2 INT )

    INSERT A VALUES (2,NULL,1)
    INSERT A VALUES (3,NULL,1)
    INSERT A VALUES (4,NULL,1)
    INSERT A VALUES (5,NULL,1)
    INSERT A VALUES (2,NULL,1)

    INSERT B VALUES (2,7)
    INSERT B VALUES (12,7)
    INSERT B VALUES (2,7)
    INSERT B VALUES (2,7)
    INSERT B VALUES (2,17)
    INSERT B VALUES (2,70)

    INSERT B VALUES (22,1)

    SELECT * FROM A

    UPDATE A SET a2=(SELECT TOP 1 b2 FROM B WHERE NOT EXISTS
    (SELECT 1 FROM A T2 WHERE A.a1=T2.a1 AND A.a2=B.B2 )
    ORDER BY NEWID())

    SELECT * FROM A

    SELECT * FROM B

    DROP TABLE A

    DROP TABLE B

如果你提供create和insert语句来快速诊断问题会更好。