简体   繁体   English

交换 PostgreSQL 中的列值

[英]Swapping column values in PostgreSQL

In my PostgreSQL database, I have a table with two text values, t1 and t2 :在我的PostgreSQL数据库中,我有一个包含两个文本值t1t2的表:

|   id   |   t1   |   t2   |  
|   1    |  abcd  |   xyz  |  
|   2    |  aazz  |   rst  |  
|   3    |  fgh   | qwerty |  

I would like to swap the values of the columns t1 and t2 for every row in the table in a way that, using the above example, this would be the result:我想交换表中每一行的t1t2列的值,使用上面的示例,结果如下:

|   id   |   t1   |   t2   |
|   1    |  xyz   |   abcd |
|   2    |  rst   |   aazz |
|   3    | qwerty |   fgh  |

Also, let's suppose the values from all rows with id=4 onwards (4, 5, 6...) are already correct, is it possible to filter which rows I want to swap?另外,假设所有 id=4 (4、5、6...)的行的值已经正确,是否可以过滤我想要交换的行?
I've tried this (for MySQL Databases) but none of the solutions worked.我已经尝试过(对于 MySQL 数据库),但没有一个解决方案有效。

That's a simple UPDATE:这是一个简单的更新:

update the_table
  set t1 = t2, 
      t2 = t1
where id < 4;

Unlike MySQL, Postgres does this correctly.与 MySQL 不同,Postgres 正确地做到了这一点。

select * from swapit;
 id |  t1   |   t2
----+-------+--------
  1 | abcd  | xyz
  2 | aazz  | rst
  3 | fgh   | qwerty
  4 | first | second
  5 | first | second
(5 rows)

update swapit set t1 = t2, t2 = t1 where id <= 3;
UPDATE 3

select * from swapit order by id;
 id |   t1   |   t2   
----+--------+--------
  1 | xyz    | abcd
  2 | rst    | aazz
  3 | qwerty | fgh
  4 | first  | second
  5 | first  | second
(5 rows)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM