2013-05-03 54 views
0

我被告知刪除工會並將查詢的上半部分改爲一個,我被告知這很容易,但我無法弄清楚。有人告訴我,這將包括像從查詢中刪除聯合並將其轉換爲一個查詢?

凡紅(主要顏色)=紅(SilksName) 凡藍(主要顏色)=藍(SilksName) 等

Select S.[Silks_Skey] 
    from [dbo].[Silks] S 
    inner join [dbo].[SubColour] SC on CHARINDEX(SC.[SubColour],S.[SilksName]) <> 0 
    inner join [dbo].[MajorColour] MC on SC.[MajorColour] = MC.[MajorColour] 

    UNION ALL 

    Select S.[Silks_Skey], MC.[MajorColour_Skey] 
    from [dbo].[Silks] S 
    inner join [dbo].[MajorColour] MC on CHARINDEX(MC.[MajorColour],S.[SilksName]) <> 0 

    ORDER BY S.[Silks_Skey] 
+3

這聽起來像你應該特別提出的** **誰告訴你「刪除工會」,並且「這很容易」,並且「它將包括類似於......的東西......」 – AakashM 2013-05-03 10:04:20

回答

0

想通了謝謝

Select S.[Silks_Skey], MC.[MajorColour_Skey] 
from [dbo].[Silks] S 
left join [dbo].[SubColour] SC on CHARINDEX(SC.[SubColour],S.[SilksName]) <> 0 
inner join [dbo].[MajorColour] MC on SC.[MajorColour] = MC.[MajorColour] 
or CHARINDEX(MC.[MajorColour],S.[SilksName]) <> 0 
1

我看不出有任何理由爲什麼你應該從查詢中刪除UNION ALL,它是最好的選擇,儘管你可以在UNION移動到一個子查詢:

SELECT S.[Silks_Skey], c.[MajorColour_Skey] 
FROM [dbo].[Silks] S 
     INNER JOIN 
     ( SELECT [Colour] = sc.[SubColour], mc.[MajorColour_Skey] 
      FROM [dbo].[SubColour] sc 
        INNER JOIN [dbo].[MajorColour] mc 
         ON sc.[MajorColour] = mc.[MajorColour] 
      UNION ALL 
      SELECT mc.[MajorColour], mc.[MajorColour_Skey] 
      FROM [dbo].[MajorColour] mc 
     ) c 
      ON CHARINDEX(c.[Colour], S.[SilksName]) <> 0 

如果HAVE刪除UNION,你可以這樣做:

SELECT S.[Silks_Skey], mc.[MajorColour_Skey] 
FROM [dbo].[Silks] S 
     LEFT JOIN [dbo].[SubColour] sc 
      ON CHARINDEX(sc.[SubColour], S.[SilksName]) <> 0 
     INNER JOIN [dbo].[MajorColour] mc 
      ON CASE WHEN sc.SubColour IS NOT NULL AND mc.MajourColour = sc.MajourColour THEN 1 
        ELSE CHARINDEX(mc.[MajorColour], S.[SilksName]) <> 0 
       END <> 0 

但我不能想象這個執行比UNION更好。

注意我的hve剛剛看到你的答案,我會選擇在加入,而不是ORCASE,case語句會帶有短路,所以當一個subcolour存在,它不評估的第二部分,而OR將評估兩者。