I have a table name table
like this
| label_id| label_name | user_id|
----------------------------------
| 1 | insvt1 | 1 |
| 2 | invest2 | 1 |
| 3 | invest3 | 1 |
| 4 | ivsest3 | 2 |
| 5 | invest4 | 3 |
I want to update this user_id column for user_id 1,1,1 with user_id 2
if label_name not same in case label name same like row 3 and row 4 then no update will occur
The result should be like this after update
| label_id| label_name | user_id|
----------------------------------
| 1 | insvt1 | 2 |
| 2 | invest2 | 2 |
| 3 | invest3 | 1 |
| 4 | ivsest3 | 2 |
| 5 | invest4 | 3 |
I have tried this
UPDATE data_table t, data_table t1
SET t.user_id = 2
WHERE t.label_name <> t1.label_name (!= this also)
AND (t.user_id = 1 or t1.user_id=2)
it's updating but also update where both lebel_name same
Any help will be appreciated
the code below should do it:
update data_table
SET [user_id] = 2
WHERE label_name IN ( SELECT label_name FROM data_table GROUP BY label_name HAVING COUNT(*) = 1) AND [user_id] = 1
Explanation: you update the data table, but ONLY those rows, for which the label description occurs only once. so that criteria i wrote in the label_name IN (....)
You code looks like MySQL. That suggests using JOIN
for the logic:
UPDATE data_table t JOIN
(SELECT label_name, COUNT(*) as cnt
FROM data_table t1
GROUP BY label_name
HAVING COUNT(*) = 1
) tt
ON t.label_name = tt.label_name
SET t.user_id = 2
WHERE t.user_id = 1;
In Postgres, this looks like:
UPDATE data_table t
SET t.user_id = 2
FROM (SELECT label_name, COUNT(*) as cnt
FROM data_table t1
GROUP BY label_name
HAVING COUNT(*) = 1
) tt
WHERE t.label_name = tt.label_name AND t.user_id = 1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.