Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Distinct in SQL Update

Here is the Select I need to convert to an Update:

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%'

My attempt:

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%'

Not sure how to apply Distinct

like image 578
Earl Avatar asked Aug 23 '11 15:08

Earl


2 Answers

Based on your comment, all of the matching rows should be updated you don't need distinct. Just execute this:

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%'

Everything that you saw in your select will be updated.

like image 200
Abe Miessler Avatar answered Nov 10 '22 10:11

Abe Miessler


Option 1: Use a temporary table to hold your initial query results, then update based on the query results.

Option 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%'
like image 23
Jeremy F. Avatar answered Nov 10 '22 11:11

Jeremy F.