【发布时间】:2021-12-23 07:19:09
【问题描述】:
我需要你的帮助来处理 3 个表的 SQL 查询。
第一个表(#chats) 聊天ID;第一个用户ID;第二个用户ID
第二张表(#users) 用户身份;用户昵称
第三张表(#messages) 消息ID,聊天ID; messageToWalletId;读取指标
我需要接收:
- 所有#chats 列表 WHERE firstUserId = ?或 secondUserId = ?
- 对于 1) 的特定输出,从关系 chats.firstUserId=users.userId + chats.secondUserId=users.userId 的表 users 中添加 userNickname
- 从#messages 表中仅获取最后一条消息,并从第 1 点返回“messageToWalletId”和“readIndicator”WHERE chatId = chatId)(ps:有更多消息发送到同一个 chatId,因此只有最后一条消息(按 messageId 排序)
前两点很简单:
$queryGetChats = '
SELECT
t1.chatId, t1.firstUserId, t1.secondUserId,
t2.userNickname AS firstUserNickname,
t3.userNickname AS secondUserNickname
FROM chat AS t1
LEFT JOIN users AS t2 ON t1.firstUserId = t2.userId
LEFT JOIN users AS t3 ON t1.secondUserId = t3.userId
WHERE firstUserId = ? OR secondUserId = ?
ORDER BY t1.chatId DESC;
';
$paramsChats = (array($userId, $userId));
return Db::queryAll($queryGetChats, $paramsChats);
但是如果我需要使用表#chats 中的 chatId 创建 WHERE 子句,我无法弄清楚第三个,它不能传递给 LEFT JOIN (SELECT ...)。
所以输出会有一个数组: array(chatId, firstUserId, secondUserId, firstUserNickname, secondUserNickname, messageToWalletId, readIndicator)
感谢您的帮助
【问题讨论】:
-
我忘了提到输出可能包含更多聊天,因此返回多数组。我得到“操作数应包含 1 列”。所以调用可能发生:1)用户有 5 个聊天(基于 SELECT 条件)2)每个聊天返回数组,包括提到的字段 3)最终将返回聊天数组数组