I have a table vehicle with columns id, model, colour, is_default.
in this is_default is a newly added column and we have 4000 old recored before adding is_primary.
the default value for is_primary is 0.
I want to fill this column for all the present records in such a way that
- A model can have multiple colours, but can only have one colour as is_default = 1. All others will be false (0).
- If a model already has a default colour then the query should not touch any records related to that model
Note: We have 1000 models and 50 colours possible
I tried below solution
UPDATE
vehicle AS scl
JOIN (
SELECT model, MIN(id) AS min_id
FROM vehicle
WHERE is_default = 0
GROUP BY model) AS sc
ON scl.model sc2.model AND scl.id= sc2.min_id
SET scl.is_default = 1;
but when I execute this it updates records which already have a default colour.
2
Answers
Your
WHERE
clause isn’t excluding the entire model whenis_default = 1
, it’s just ignoring those rows when findingMIN(id)
for the model. Use a subquery to exclude all the rows with that model.This will do it:
See it here:
However, it will set every row… just to the same existing value in cases where that is desired. The trick there is using the
ORDER BY
within the window to sort the current default first.