哪一行违反了这个检查约束?

What row is violating this check constraint?

我正在尝试将以下检查约束添加到 raffle_participant table:

ALTER TABLE raffle_participant ADD CONSTRAINT ck_raffle_participant_total_purchased_le_ticket_limit CHECK (tickets_purchased_in_raffle(raffle_id) <= get_ticket_limit(raffle_id))

当我执行上面的命令时,我得到了:

ERROR:  check constraint "ck_raffle_participant_total_purchased_le_ticket_limit" of relation "raffle_participant" is violated by some row

在我看来 raffle_participant table 中的所有行都满足约束条件。我在这里不明白什么?为什么现有数据违反了检查约束?

使用 PostgreSQL 版本 13.6。

编辑: 我已经尝试了以下查询来找出哪些行违反了约束,并且看起来 none 确实如此。

development=# select (select sum(p.tickets_purchased) from raffle_participant p where p.raffle_id = 2) <= (select r.ticket_limit from raffle r where r.id = 2);
 ?column? 
----------
 t
(1 row)

development=# select (select sum(p.tickets_purchased) from raffle_participant p where p.raffle_id = 3) <= (select r.ticket_limit from raffle r where r.id = 3);
 ?column? 
----------
 t
(1 row)

development=# select (select sum(p.tickets_purchased) from raffle_participant p where p.raffle_id = 4) <= (select r.ticket_limit from raffle r where r.id = 4);
 ?column? 
----------
 t
(1 row)

抽奖table

架构

Column Type Collation Nullable Default
id integer not null generated always as identity
item_name character varying(40) not null
item_value bigint not null
ticket_limit integer not null
ticket_price bigint not null
user_ticket_limit integer not null
ended_on timestamp with time zone
winner_id bigint

数据

id item_name item_value ticket_limit ticket_price user_ticket_limit ended_on winner_id
1 item 10 10 10 2 2022-04-27 17:46:01.271025+00
2 item 10 10 10 10 2022-04-27 17:55:28.783744+00 151150118697959424
3 item 10 10 10 10 2022-04-27 20:32:13.588843+00 151150118697959424
4 item 10 10 10 10

raffle_participant table

架构

Column Type Collation Nullable Default
raffle_id integer not null
user_id bigint not null
tickets_purchased integer not null

数据

raffle_id user_id tickets_purchased
2 151150118697959424 10
3 151150118697959424 10
4 151150118697959424 3

tickets_purchased_in_raffle函数

CREATE FUNCTION tickets_purchased_in_raffle (IN raffle_id raffle.id%TYPE) 
  RETURNS raffle_participant.tickets_purchased%TYPE AS
  $$ 
    SELECT SUM(p.tickets_purchased) FROM raffle_participant p WHERE p.raffle_id = raffle_id 
  $$
LANGUAGE SQL

get_ticket_limit 函数

CREATE FUNCTION get_ticket_limit (IN raffle_id raffle.id%TYPE) 
  RETURNS raffle.ticket_limit%TYPE AS
  $$
    SELECT r.ticket_limit FROM raffle r WHERE r.id = raffle_id 
  $$
LANGUAGE SQL

问题是 tickets_purchased_in_raffle 的输入参数 raffle_idraffle_participant 的列名称 raffle_id 遮盖了。通过将参数名称更改为 rid,我能够成功添加检查约束。