在前一行上有条件插入

jw5wzhpr  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(314)

我有一个 players 具有以下定义的表:

Column    |            Type             | Collation | Nullable |               Default
-------------+-----------------------------+-----------+----------+-------------------------------------
 id          | integer                     |           | not null | nextval('players_id_seq'::regclass)
 player_name | character varying(64)       |           | not null |
 server_name | character varying(64)       |           | not null |
 joined_at   | timestamp without time zone |           | not null |

其数据如下:

id | player_name | server_name  |         joined_at
----+-------------+--------------+----------------------------
  1 | Jane        | blue-server  | 2021-04-27 10:42:51.986282
  2 | Matt        | red-server   | 2021-04-27 10:42:51.986282
  3 | Jane        | green-server | 2021-04-27 10:42:51.986282
  4 | Jane        | blue-server  | 2021-04-27 10:42:51.986282

我创造了一个db小提琴。
所需查询
我想写一封信 insert 谁的成功取决于 player_name 以及 server_name 价值观。如果给定的 player_name 以及 server_name 如果组合匹配,那么insert应该失败,否则,insert应该继续。
因此,在上述情况下,以下插入应失败:

insert into players (player_name, server_name, joined_at) values ('Matt', 'red-server', now());

因为最后一张唱片 player_name = 'Matt' 也有同样的 server_name = 'red-server' 但是,这两种方法都应该成功:

insert into players (player_name, server_name, joined_at) values ('Matt', 'grey-server', now());
insert into players (player_name, server_name, joined_at) values ('Matt', 'red-server', now());

我希望这是有道理的。这是另一个例子。以下操作应失败:

insert into players (player_name, server_name, joined_at) values ('Jane', 'blue-server', now());

我不知道如何在sql中实现这一点。

fykwrbwg

fykwrbwg1#

创建一个cte,返回要插入和使用的列值 INSERT ... SELECT 来自cte的 WHERE 从句代替 INSERT ... VALUES :

WITH cte(player_name, server_name, joined_at) AS (SELECT 'Matt', 'red-server', now())
INSERT INTO players (player_name, server_name, joined_at) 
SELECT c.*
FROM cte c
WHERE c.server_name <> 
      COALESCE((SELECT p.server_name FROM players p WHERE p.player_name = c.player_name ORDER BY joined_at DESC LIMIT 1), '')

请看演示。

相关问题