I have a table with a column with repeating values, and I want to add another column that has unique values for each distinct value in the first column.Here is a sample:
temp Postal
1 42420
2 90032
3 60610
4 42420
5 98661
6 10024
7 10024
8 10024
Considering the above example, row 1 and 4 should have the same value , while 6,7 and 8 should share a value as well.
I wrote a query that implements my intended feature but on a limited scale:
UPDATE `train`
SET `new_column`=(SELECT MIN(temp) FROM train WHERE `Postal`= '42420')
WHERE `Postal`='42420';
This works well but is unscalable for large datasets(the one I am using has 9801 rows). Is there away to make it work automatically for the whole table?
2
Answers
If you’re running MySQL 8+, or a recent version of MariaDB, then I suggest not doing this update. The reason is that any time your data changes, e.g. by adding a new record with the same
Postal
value, you might be forced to run the update again. Instead, just use the following select query:You could place this query into a view for easy access. This query should benefit from the following index:
You can do it using
group by
to get the smallest temp by Postal, then usinginner join
to get the smallest temp per record :Result :
Demo here