0

Consider a table "users" as below:

id, add_id, add
1, 1, abc
2, null, abc
3, null, xyz
4, 2, xyz

Expected output:

id, add_id, add
1, 1, abc
2, 1, abc
3, 2, xyz
4, 2, xyz

Please suggest a MySQL query to get the desired result.

2 Answers 2

1

A simple method uses window functions:

select id, max(add_id) over (partition by add), add
from t;

If you want to change the value, then the update would be:

update t join
       (select add, max(add_id) as add_id
        from t
        group by add
       ) tt
       on t.add = tt.add
    set t.add_id = tt.add_id
    where t.add_id is null;
Sign up to request clarification or add additional context in comments.

Comments

1

You can select the id From the table.

if you have more than 1 row with and aff_id and add, then you must LIMIT the inner SELECT

CREATE TABLE table1 (
  `id` INTEGER,
  `add_id` VARCHAR(4),
  `add` VARCHAR(3)
);

INSERT INTO table1
  (`id`, `add_id`, `add`)
VALUES
  ('1', '1', 'abc'),
  ('2', null, 'abc'),
  ('3', null, 'xyz'),
  ('4', '2', 'xyz');
UPDATE table1 t2 
SET `add_id` = (SELECT `add_id` FROM (SELECT * FROM table1) t1 WHERE t1. `add` = t2.`add` AND `add_id` IS NOT NULL) 
WHERE `add_id` IS NULL
SELECT * FROM table1
id | add_id | add
-: | :----- | :--
 1 | 1      | abc
 2 | 1      | abc
 3 | 2      | xyz
 4 | 2      | xyz

db<>fiddle here

1 Comment

t2 is the alias of the updated table, as you use the same table for updateing and getting the information, you must use aliases, so that mysql can differentiate them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.