在SQL Update中使用Distinct

时间:2011-08-23 15:09:15

标签: sql sql-server sql-update distinct

以下是我需要转换为更新的选择:

SELECT DISTINCT f.SectionID, f.Name, v.Enabled
FROM SETTING_VALUE v
INNER JOIN SETTING s ON v.SettingID = s.SettingID
INNER JOIN LU_FIELD f ON f.FieldID = s.FieldID
WHERE v.DisplayValue LIKE '%Miami%'
AND f.ControlName LIKE '%City%'

我的尝试:

UPDATE SETTING_VALUE
SET Enabled = 0
FROM SETTING_VALUE v
INNER JOIN SETTING s ON v.SettingID = s.SettingID
INNER JOIN LU_FIELD f ON f.FieldID = s.FieldID
WHERE v.DisplayValue LIKE '%Miami%'
AND f.ControlName LIKE '%City%'

不确定如何应用Distinct

4 个答案:

答案 0 :(得分:8)

根据您的评论all of the matching rows should be updated,您不需要区分。只需执行此操作:

UPDATE SETTING_VALUE
SET Enabled = 0
FROM SETTING_VALUE v
INNER JOIN SETTING s ON v.SettingID = s.SettingID
INNER JOIN LU_FIELD f ON f.FieldID = s.FieldID
WHERE v.DisplayValue LIKE '%Miami%'
AND f.ControlName LIKE '%City%'

您在选择中看到的所有内容都将更新。

答案 1 :(得分:2)

选项1:使用临时表来保存初始查询结果,然后根据查询结果进行更新。

选项2:

Insert into SETTING_VALUE
(SectionID, Name, Enabled)
SELECT DISTINCT f.SectionID, f.Name, v.Enabled
FROM SETTING_VALUE v
INNER JOIN SETTING s ON v.SettingID = s.SettingID
INNER JOIN LU_FIELD f ON f.FieldID = s.FieldID
WHERE v.DisplayValue LIKE '%Miami%'
AND f.ControlName LIKE '%City%'

答案 2 :(得分:1)

UPDATE SETTING_VALUE
   SET Enabled = 0
 WHERE DisplayValue LIKE '%Miami%'
       AND EXISTS (
                   SELECT *
                     FROM SETTING s 
                    WHERE SETTING_VALUE.SettingID = s.SettingID
                          AND EXISTS (
                                      SELECT *
                                        FROM LU_FIELD f 
                                       WHERE f.FieldID = s.FieldID
                                             AND f.ControlName LIKE '%City%'
                                     )
                  );

答案 3 :(得分:0)

您可以尝试以下

UPDATE v
SET Enabled = 0 
FROM SETTING_VALUE v 
WHERE EXISTS(
   select * from SETTING s 
   INNER JOIN LU_FIELD f ON f.FieldID = s.FieldID 
   WHERE v.DisplayValue LIKE '%Miami%' 
   AND f.ControlName LIKE '%City%' 
   AND v.SettingID = s.SettingID
)