2015-05-19 70 views
0

我有一個500行的表和750行左右的另一個表。我正在做的是,我從第二個表中隨機獲得500行的特定列,並且我想用這500個值更新第一個表上新添加的列。更新表的所有行的列

我知道該怎麼做看起來像這樣的更新:

UPDATE schema.table1 
SET column = cl.column FROM schema.table1 cl 
INNER JOIN table2 cf ON cf.column = cl.column 

,但我並沒有被這兩個表中匹配任何列。有沒有辦法做到這一點,而不必匹配內部聯接的列?

所以基本上,我想更新500行1列在一個表中,有500個值從另一個表

+0

這是MySql還是SQL Server?答案取決於你正在使用哪一個。 –

+0

@MauriceReeves sql服務器管理工​​作室 –

+0

所以你沒有匹配的列,但你想使用內部連接。首先告訴我們爲什麼你想更新沒有邏輯? – Imran

回答

1

未來您可以通過使用ROW_NUMBER產生柱連接兩張表做。看看這個例子和輸出

DECLARE @T1 TABLE (column1 INT ,column2 VARCHAR(2)) 

DECLARE @T2 TABLE (column1 VARCHAR(2)) 

INSERT INTO @T1 (column1, column2) 
     VALUES (0, 'A'), (1, 'B'), (2, 'C') 

INSERT INTO @T2 (column1) 
    VALUES ('D'),('F'),('G') 


SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL)) AS RN FROM @T1 
SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL)) AS RN FROM @T2 

;WITH CTE_1 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL)) AS RN FROM @T1) 
    ,cte_2 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL)) AS RN FROM @T2) 
UPDATE t1 
SET t1.column2 = t2.column1 
FROM CTE_1 t1 
JOIN cte_2 t2 
ON t1.rn = t2.rn 

SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL)) AS RN FROM @T1 
SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL)) AS RN FROM @T2