PostgreSQL에서 :
CREATE TABLE users (
users_id serial PRIMARY KEY,
name text UNIQUE NOT NULL
);
CREATE TABLE friends (
friends_id serial PRIMARY KEY,
timestamp TIMESTAMPTZ default now(),
user_a integer NOT NULL REFERENCES users,
user_b integer NOT NULL REFERENCES users,
status integer NOT NULL default 2
)
우정을 목록으로 보려면 :
CREATE VIEW friendships AS
SELECT DISTINCT user_a, user_b FROM friends WHERE status = 1
UNION
SELECT DISTINCT user_b, user_a FROM friends WHERE status = 1;
다음과 같이 사용할 수 있습니다.
INSERT INTO users ( name ) VALUES ( 'foo' );
INSERT INTO users ( name ) VALUES ( 'bar' );
INSERT INTO users ( name ) VALUES ( 'baz' );
SELECT * FROM users;
users_id | name
----------+------
1 | foo
2 | bar
3 | baz
INSERT INTO FRIENDS ( user_a, user_b, status ) VALUES ( 1, 2, 1 );
INSERT INTO FRIENDS ( user_a, user_b, status ) VALUES ( 2, 1, 1 );
INSERT INTO FRIENDS ( user_a, user_b, status ) VALUES ( 1, 3, 1 );
SELECT * FROM friendships ORDER BY user_a, user_b;
user_a | user_b
--------+--------
1 | 2
1 | 3
2 | 1
3 | 1
SELECT a.name, b.name
FROM friendships
JOIN users a ON a.users_id = user_a
JOIN users b ON b.users_id = user_b
ORDER BY a.name, b.name;
name | name
------+------
bar | foo
baz | foo
foo | bar
foo | baz