[英]Update a table with where clause on a column value In Postgresql
I have a table name table
like this我有一个像这样的表
table
| 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
我想
user_id 1,1,1 with user_id 2
这个 user_id 列,如果 label_name 不同,以防 label 名称与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它正在更新,但也会更新 lebel_name 相同的地方
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.说明:您更新数据表,但仅更新那些 label 描述仅出现一次的行。 so that criteria i wrote in the label_name IN (....)
所以我在 label_name IN (....) 中写的标准
You code looks like MySQL.您的代码看起来像 MySQL。 That suggests using
JOIN
for the logic:这建议使用
JOIN
作为逻辑:
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:在 Postgres 中,这看起来像:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.