2013-08-16 93 views
-1

我希望我對此有所瞭解,但這裏有所瞭解。幫助SQL更新

我想要做的是從兩個表(通過JOIN)獲取信息,然後將這兩個表中的信息更新到第三個表中。以下是我編寫的一些測試代碼,它幾乎可以模擬我需要做的事情。

我唯一的問題是,在最後的「SELECT * FROM @tempTable」中...我不確定如何獲取UPDATE以處理@tempTable表中的userName和badgeId列。我試過的所有東西最終都會插入到它自己的行中,就像我正在執行INSERT一樣......

任何幫助表示讚賞。我在MS SQL Server 2008 R2中編寫並運行了代碼,因此它應該可以工作。

/* Create the 'Users' table */ 

DECLARE @Users TABLE(
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    userName varchar(100), 
    UserId int) 

INSERT INTO @Users (userName, UserId) 
VALUES ('jim', 100), 
     ('kira', 200), 
     ('ken', 300), 
     ('dan', 400), 
     ('len', 500) 

/* Create the 'Badges' table */ 
DECLARE @Badges TABLE(
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    badgeId varchar(100), 
    userId int) 

INSERT INTO @Badges (badgeId, UserId) 
VALUES (10, 100), 
     (20, 200), 
     (30, 300), 
     (40, 400), 
     (50, 500) 

/* Create the '@tempTable' */ 
DECLARE @tempTable TABLE(
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    userName varchar(100), 
    badgeId int, 
    divNumber int, 
    secNumber int) 

INSERT INTO @tempTable (badgeId, userName, divNumber, secNumber) 
VALUES (null, null, 68, 34), 
     (null, null, 68, 34), 
     (null, null, 69, 24), 
     (null, null, 69, 24), 
     (null, null, 70, 14) 

/* Select userNames and badgeIds from the 'Users' and 'Badges' tables */  
SELECT u.userName, b.badgeId 
FROM @Users as u 
    INNER JOIN @Badges as b 
    ON b.userId = u.UserId 

/* Select all information from the '@tempTable' table */ 
SELECT * FROM @tempTable 

enter image description here

+0

除了你應該更好地設置問題的格式,你使用的數據庫是什麼?你已經標記爲「mysqli」。但是語法看起來像SQL Server。 –

回答

1

如果我理解你的要求正確嘗試使用此更新語句結尾。

update @tempTable 
set userName = u.userName, 
badgeId = b.badgeId 
FROM @Users as u 
INNER JOIN @Badges as b 
ON b.userId = u.UserId 
+0

邁克,感謝您的幫助!像魅力一樣工作。我認爲我的問題是我加入了「ON userName = null」。乾杯! – SalarianEngineer

+0

是的,只是等了5分鐘才讓我標記爲答案。再次感謝;-) – SalarianEngineer

+0

對不起,不耐煩,我有點新 – MikeD