2010-02-13 69 views
1

的號碼,我旁邊有近似的表結構:T-SQL查詢,以檢查存在物

accounts: 
ID INT, 
owner_id INT, 
currency_id TINYINT 

相關

clients: 
ID INT 

currency_types: 
ID TINYINT, 
name NVARCHAR(25) 

我需要寫一個存儲過程檢查是否存在具有特定貨幣和所有其他貨幣的賬戶,即客戶可以使用特定貨幣賬戶和其他賬戶encies和兩者。

我已經寫此查詢:

SELECT 
    ISNULL((
    SELECT 1 
    WHERE EXISTS 
    (
     SELECT 1 
     FROM [accounts] AS A, [currency_types] AS CT 
     WHERE 
      A.[owner_id] = @client -- sp param 
     AND A.[currency_id] = CT.[ID] 
     AND CT.[name] = N'Ruble' 
    )), 0) AS [ruble], 
    ISNULL((
    SELECT 1 
    WHERE EXISTS 
    ( 
     SELECT A.[ID] 
     FROM [accounts] AS A, [currency_types] AS CT 
     WHERE 
      A.[owner_id] = @client 
     AND A.[currency_id] = CT.[ID] 
     AND CT.[name] != N'Ruble' 
    )), 0) AS [foreign] 

是否有可能進行優化呢?我是(T)SQL的新手,非常感謝!

回答

0

這樣的查詢需要一個選擇少:

RETURN ISNULL((SELECT 1 
    WHERE 
     EXISTS 
     (
      SELECT 1 
      FROM [accounts] AS A, [currency_types] AS CT 
      WHERE 
       A.[owner_id] = @client 
      AND A.[currency_id] = CT.[ID] 
      AND CT.[name] != N'Ruble' 

     ) 
    ), 0) 
1

對我來說似乎很合理,EXISTS會給這種事情帶來好的表現。

您是否有理由認爲需要優化?它表現糟糕嗎?

,以確保關鍵的是,你有合適的指標(如應收[owner_id],CT.ID顯然是一個PK。)

+0

@ AdaTheDev:我是新來的SQL,所以只是擔心,因爲查詢有3個SELECTs ..和兩個WHERE條件非常相似,所以也許他們可以拆分成單一但複雜的東西。 – abatishchev 2010-02-13 20:44:07

+1

外部選擇不會花費太多(可忽略)。爲了實現你想要的,我實際上認爲這種方法很好 - 看不到一個簡單的方法來達到同樣的結果。複雜性通常會使事情變得更糟,因爲它可能使SQL Server更難以優化查詢 – AdaTheDev 2010-02-13 21:14:26