有一个名为payment_history
的表。
payment_history
id
status_name
added_at
user_id
有3种状态:paid, pre_active
和active
。只有一个状态为" active
"对于给定的用户。为简单起见,假设字段状态为varchar
(status_name
)类型,而不是integer
(那么它将是status_id
)。我想知道某个特定用户(user_id
)是否处于活动状态。
a)如果用户不
a1)如果至少有一行状态为" pre_active
"存在(可能有很多),找到最旧的(added_at
)并使其成为" active
"
a2)如果没有,则找到状态为" paid
"的行,将所有这些行" pre_active
"并且,再次找到最旧的一个(added_at
)并使其成为" active
"
b)如果用户确实(状态为" active
"):
b1)只是raise
通知说这个。
这是我的功能:
CREATE OR REPLACE FUNCTION update_payment_history(user_id integer)
RETURNS SETOF void AS
$BODY$
BEGIN
--1
-- if there is no active status
IF NOT EXISTS (
SELECT id FROM payment_history WHERE status_name = 'active' and user_id = $1
) THEN
-- if pre_active exists then select the oldest one and make it active
IF EXISTS (
SELECT id FROM payment_history WHERE status_name = 'pre_active' and user_id = $1
) THEN
-- todo make a function to get rid of the repetition?
UPDATE payment_history
SET status_name = 'active'
WHERE p.user_id = $1
AND status_name = 'pre_active'
ORDER BY added_at DESC LIMIT 1;
ELSE
UPDATE payment_history
SET status_name = 'pre_active'
WHERE p.user_id = $1
AND status_name = 'paid';
-- todo make a function to get rid of the repetition?
UPDATE payment_history
SET status_name = 'active'
WHERE p.user_id = $1
AND status_name = 'pre_active'
ORDER BY added_at DESC LIMIT 1;
END;
ELSE
RAISE NOTICE 'the user has the status active'
RETURN;
END IF;
END;
$BODY$
首先,我想可能有一种更简单的方法来实现这一点,因为这里有太多的代码重复。
其次,我猜EXISTS
和NOT EXISTS
函数可以替换为更合适的东西(只是我的猜测)。
你的想法?