mysql中的php子选择数组

xuo3flqw  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(311)

我有以下表格:
聊天用户

chatId   | userId        |
---------|---------------|
1        | 1             |
1        | 2             |
2        | 1             |
2        | 3             |

聊天室

chatId   |lastMessageTime|
---------|---------------|
1        | yesterday     | //for example 1000000000
2        | today         | //for example 1532473344

假设我是 userId 1 我想把我现在的聊天室都装进去。
订购人 chatRooms.lastMessageTime +我想知道哪些用户在同一个聊天室( chatUsers.userId )
例如在这种情况下:

[{
   "chatId": 2,
   "users": [1, 3]
 },
 {
   "chatId": 1,
   "users": [1, 2]
 }]

有可能吗?我在没有用户选择的情况下成功做到了:

$qry = $db->prepare('SELECT cr.chatId FROM chatRooms AS cr INNER JOIN chatUsers AS cu ON cu.chatId = cr.chatId WHERE cu.userId = :userId 
  ORDER BY cr.lastMessageTime DESC, cr.chatId DESC');
$qry->bindParam(':userId', $userId, PDO::PARAM_INT);
$qry->execute();

$chatRooms = $qry->fetchAll(PDO::FETCH_ASSOC);

但我无法在select中进行子select。。

km0tfn4u

km0tfn4u1#

$qry = $db->prepare('SELECT cr.chatId, GROUP_CONCAT(cu.userId) AS users FROM chatRooms AS cr INNER JOIN chatUsers AS cu ON cu.chatId = cr.chatId WHERE cu.userId = :userId ORDER BY cr.lastMessageTime DESC, cr.chatId DESC GROUP BY chatId');
$qry->bindParam(':userId', $userId, PDO::PARAM_INT);
$qry->execute();

$chatRooms = $qry->fetchAll(PDO::FETCH_ASSOC);

这样,您就可以在逗号分隔的字符串中获得用户。

相关问题