[英]SQL Unique on join
I have an application where: 我有一个应用程序,其中:
I need to be able to 我需要能够
I am stuck on how to go about requirement 2. 我被困在如何执行要求2上。
Current Table structure: 当前表结构:
CREATE TABLE applications (
id integer NOT NULL,
user_id bigint NOT NULL,
status character varying(255) DEFAULT 'pending'::character varying NOT NULL,
active boolean DEFAULT false NOT NULL,
name character varying(255) DEFAULT NULL::character varying,
email character varying(255) DEFAULT NULL::character varying,
created_at timestamp without time zone DEFAULT now() NOT NULL,
CONSTRAINT applications_status_values CHECK (((status)::text = ANY ((ARRAY['pending'::character varying, 'approved'::character varying, 'rejected'::character varying, 'archived'::character varying])::text[])))
);
An example of a document kind: 文档类型的示例:
CREATE TABLE pan (
id bigint NOT NULL,
value character(10) NOT NULL,
status document_statuses DEFAULT 'pending'::document_statuses,
extra_data json,
verified_at timestamp without time zone,
reject_reason character varying,
application_id bigint NOT NULL
);
Taking a look to your model I think there is a concept error. 看一下您的模型,我认为存在概念错误。
You say: No document can be re-used across multiple applications belonging to 2 different users 您说:不能在属于2个不同用户的多个应用程序之间重用文档
So, this in other terms is that the document only can be re-used in any other app if the user is the same. 因此,换句话说,如果用户相同,则该文档只能在任何其他应用程序中重复使用。 So, we can go a high level and understant that each document has a user_owner, and while this document is used by this user all is correct.
因此,我们可以更深入地了解每个文档都有一个user_owner,并且此用户使用此文档时,所有文档都是正确的。
Then, what I suggest is the simple solution: 然后,我建议的是简单的解决方案:
ALTER TABLE pan ADD COLUMN user_id bigint NOT NULL REFERENCES user (user_id);
And then Update this field with the correct value. 然后使用正确的值更新此字段。 This will simplify your solution and also add a reference to the user that generated the document.
这将简化您的解决方案,并为生成文档的用户添加参考。
EDIT: 编辑:
Add this trigger, thills will call a procedure with the update sentence: 添加此触发器,thill将使用更新语句调用一个过程:
CREATE TRIGGER t_document_owner
AFTER UPDATE ON applications
FOR EACH ROW
WHEN (OLD.user_id IS DISTINCT FROM NEW.user_id)
EXECUTE PROCEDURE p_update_document_owner(NEW.user_id,OLD.user_id);
This is a basic proposal for the update procedure: 这是更新过程的基本建议:
CREATE FUNCTION p_update_document_owner(new_user_id,old_user_id) RETURNS VOID
AS
'
UPDATE pan
SET user_id=$1
WHERE user_id =
(SELECT user_id
FROM (
SELECT user_id
FROM pan WHERE
user_id=$2
)as aux
)
'LANGUAGE SQL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.