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