【发布时间】:2015-11-20 20:15:53
【问题描述】:
我有两张桌子;朋友和用户。
用户表,略微简化:
CREATE TABLE users (
id bigserial NOT NULL,
fname text,
lname text,
username text,
created timestamp without time zone DEFAULT now(),
CONSTRAINT users_pkey PRIMARY KEY (id)
)
Friends 表是一个连接表
CREATE TABLE friends
(
user_id bigint,
friend_id bigint,
accepted boolean DEFAULT false
)
所以朋友表只是将一个用户映射到另一个用户,所以用户 1 可以与用户 2 成为朋友。
我的问题:如何约束表格,使两对 (1, 2) , (2,1) 不会插入表格中?
我知道我可以使用unique (user_id , friend_id) 来防止插入像 (1,2) 这样的重复行...
但是如果 (1, 2) 已经存在,如何防止插入 (2, 1)?
【问题讨论】:
标签: sql postgresql