我被告知删除联盟并将查询的上半部分更改为一个,我被告知这很容易,但我无法弄明白。我被告知它会包含类似
的内容红色(主要颜色)=红色(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]
答案 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
如果已要删除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更好。
注意我刚刚看到你的回答,我会选择联接中的CASE
而不是OR
,case语句会短路,所以当子颜色存在时它不会评估第二部分,而OR将评估两者。
答案 1 :(得分: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