我为我的问题准备了一个简单的SQL Fiddle。
在 PostgreSQL 10 中有 2 个表保存用户 ID 和用户社交网络数据(如名字、照片):
CREATE TABLE words_users (
uid SERIAL PRIMARY KEY
);
CREATE TABLE words_social (
sid text NOT NULL,
social integer NOT NULL CHECK (0 < social AND social <= 64),
given text NOT NULL CHECK (given ~ '\S'),
uid integer NOT NULL REFERENCES words_users ON DELETE CASCADE,
PRIMARY KEY(sid, social)
);
并且有 2 张桌子存放游戏和聊天消息:
CREATE TABLE words_games (
gid SERIAL PRIMARY KEY,
player1 integer REFERENCES words_users(uid) ON DELETE CASCADE NOT NULL CHECK (player1 <> player2),
player2 integer REFERENCES words_users(uid) ON DELETE CASCADE
);
CREATE TABLE words_chat (
cid BIGSERIAL PRIMARY KEY,
created timestamptz NOT NULL,
gid integer NOT NULL REFERENCES words_games ON DELETE CASCADE,
uid integer NOT NULL REFERENCES words_users ON DELETE CASCADE,
msg text NOT NULL
);
在这里,我用测试数据填充表格:
- Facebook 上 uid=1 和 sid="1111" 的用户“Alice”(social=10)
- Google 上 uid=2 和 sid="2222" 的用户“Bob”(social=20)
- gid=100 的游戏,两个用户都可以聊天
SQL:
INSERT INTO words_users (uid) VALUES (1), (2);
INSERT INTO words_games (gid, player1, player2) VALUES (100, 1, 2);
INSERT INTO words_social (sid, social, given, uid) VALUES
('1111', 10, 'Alice', 1),
('2222', 20, 'Bob', 2);
INSERT INTO words_chat (created, gid, uid, msg) VALUES
(now() + interval '1 min', 100, 2, 'Hello, Alice'),
(now() + interval '2 min', 100, 1, 'Hello, Bob'),
(now() + interval '3 min', 100, 2, 'Nice to see you, Alice'),
(now() + interval '4 min', 100, 1, 'Nice to see you too, Bob'),
(now() + interval '5 min', 100, 2, 'Goodbye, Alice'),
(now() + interval '6 min', 100, 1, 'Goodbye, Bob');
我正在尝试创建一个 PHP 脚本,当给定sid、social和gid时,它将返回游戏 gid 的完整聊天。
我不只是使用gid参数来获取和显示聊天,因为我不希望其他用户监视他们不玩的游戏。
另外我不能使用uid参数来识别调用我的脚本的用户,我必须使用sid和social参数(加上一个秘密,我从上面的测试用例中省略了)。
所以这是我获取聊天的 SQL 语句:
SELECT uid, msg
FROM words_chat
WHERE gid=100
AND EXISTS (select 1 from words_games where
(select uid from words_social
where sid='1111' and social=10) in (player1, player2))
ORDER BY CREATED ASC;
它有效,但我还需要 1 件事,这使得它变得复杂 - 对于每个聊天消息,我需要一个布尔值(而不是uid)来知道这是否是“爱丽丝”的消息(这样我就可以画出那条线粗体字)。
所以我正在尝试这样做,而 SQL 语句变得更加丑陋:
SELECT uid=(select uid from words_social
where sid='1111' and social=10) AS mine, msg
FROM words_chat
WHERE gid=100
AND EXISTS (select 1 from words_games where
(select uid from words_social
where sid='1111' and social=10) in (player1, player2))
ORDER BY CREATED ASC;
正如您在上面的屏幕截图中看到的那样,这是可行的,但是如何改进此查询?
SQL 中有没有办法(即我不想在我的 PHP 脚本中保存uid值或使用 pl/pgSQL)在第二个子查询中重用uid ?