2012-07-03 85 views
1

這是我確切的SQL代碼,但它是非常緩慢的,我知道這很可怕......加快/更有​​效地SQL

是否有另一種方式來做到這一點,但速度更快?

UPDATE Customer SET Title = "MR", SurName = "Test", FirstName ="Bob", HomePostCode ="SW18" WHERE CustomerID IN (SELECT CxID FROM Production WHERE policy_number = "001C5T" AND member_number = "100" AND family_group = "000001" AND CxID > 0) 

感謝

+0

你有沒有在子選擇中命名的列上設置索引? –

+0

是的,他們都有相關的指標。 – ojsglobal

回答

3

試試這個(未經測試)

UPDATE Customer c 
JOIN Production p ON p.CxID = c.CustomerID 
SET c.Title = "MR", 
    c.SurName = "Test", 
    c.FirstName ="Bob", 
    c.HomePostCode ="SW18" 
WHERE p.policy_number = "001C5T" 
    AND p.member_number = "100" 
    AND p.family_group = "000001" 
    AND p.CxID > 0 
1

,您可以加入在更新的表,所以也就沒有再選擇。

+0

那會怎樣? – ojsglobal

1

我想你想是這樣的:

UPDATE customer 
SET Title = "MR", SurName = "Test", FirstName ="Bob", HomePostCode ="SW18" 
FROM customer  
inner join production on customer.customerID = production.cxid 
where policy_number = "001C5T" AND member_number = "100" AND family_group = "000001" AND CxID > 0 
1

要在krakover的答案擴展,你可以加入表:

UPDATE Customer JOIN 
Production P ON (C.CustomerID = P.CxID) 
AND (P.policy_number = "001C5T") 
AND (P.member_number = "100") 
AND (P.family_group = "000001") 
AND (P.CxID > 0) 
SET C.Title = "MR", C.SurName = "Test", C.FirstName ="Bob", C.HomePostCode ="SW18" 

請注意,請根據您的情況仔細檢查表格別名。

0

另一種方法無連接:

INSERT INTO Customer (CustomerID, Title, SurName, FirstName, HomePostCode) 
SELECT CxID, 'MR', 'Test', 'Bob', 'SW18' 
FROM Production 
WHERE policy_number = '001C5T' AND member_number = '100' AND family_group = '000001' AND CxID > 0 
ON DUPLICATE KEY UPDATE Title = VALUES(Title), SurName = VALUES(SurName), FirstName = VALUES(FirstName), HomePostCode = VALUES(HomePostCode) 

這就需要你有和選擇至少一個唯一的列。我asume CustomerID是。