簡體   English   中英

在 Postgresql 中的列值上使用 where 子句更新表

[英]Update a table with where clause on a column value In Postgresql

我有一個像這樣的表table

| label_id| label_name | user_id|
----------------------------------
|    1    | insvt1     |   1    |
|    2    | invest2    |   1    |
|    3    | invest3    |   1    |
|    4    | ivsest3    |   2    |
|    5    | invest4    |   3    |

我想user_id 1,1,1 with user_id 2這個 user_id 列,如果 label_name 不同,以防 label 名稱與row 3 and row 4 then no update will occur

更新后的結果應該是這樣的

| label_id| label_name | user_id|
----------------------------------
|    1    | insvt1     |   2    |
|    2    | invest2    |   2    |
|    3    | invest3    |   1    |
|    4    | ivsest3    |   2    |
|    5    | invest4    |   3    |

我試過這個

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)

它正在更新,但也會更新 lebel_name 相同的地方

任何幫助將不勝感激

下面的代碼應該做到這一點:

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

說明:您更新數據表,但僅更新那些 label 描述僅出現一次的行。 所以我在 label_name IN (....) 中寫的標准

您的代碼看起來像 MySQL。 這建議使用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;

在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM