简体   繁体   English

MySQL从其他表中选择昵称?

[英]Mysql select nickNames from other table?

I have 3 tables for a chat app 我有3张桌子用于聊天应用

  • chatRooms (id) chatRooms(id)

  • chatMessages (id, roomId, userId, message) chatMessages(id,roomId,userId,消息)

  • userData (userId, nickName) userData(用户ID,昵称)

How can I load all the chatRooms with the chatMessages with the nickNames? 如何加载带有nickNames的chatMessages的所有chatRoom?

I tried: 我试过了:

$qry = $db->prepare('SELECT 
        chatRooms.id,
        chatMessages.message, 
        userData.nickName 
    FROM chatRooms 
    LEFT JOIN chatMessages 
        ON chatMessages.roomId = chatRooms.id 
    LEFT JOIN userData 
        ON chatMessages.userId = userData.userId '
);
$qry->execute();

But it doesn't seem to work for me:C 但这似乎对我不起作用:C

I would like to display all the users who are in the chatRoom in the chat name 我想以聊天名称显示在chatRoom中的所有用户

So if 3 people (Fred, Joe, Bane) are in the group then I somehow would need an array with them. 因此,如果小组中有3个人(弗雷德,乔,贝恩),那么我莫名其妙地需要一个阵列。 For every array element(chatRoom) 对于每个数组元素(chatRoom)

Your first LEFT JOIN is more than likely returning more than one row. 您的第一个LEFT JOIN很可能返回多个行。

From your question, your "chatMessages" table also has a userId in it. 根据您的问题,您的“ chatMessages”表中也包含一个userId。 You should also filter by this. 您还应该对此进行过滤。

In order to do this, you would need to: 为此,您需要:

  1. Join userData before chatMessages 在chatMessages之前加入userData
  2. Include the userId from userData in the LEFT JOIN on chatMessages 将userData中的userId包括在chatMessages的LEFT JOIN中

     $qry = $db->prepare('SELECT chatRooms.id, chatMessages.message, userData.nickName FROM chatRooms LEFT JOIN userData ON chatMessages.userId = userData.userId LEFT JOIN chatMessages ON chatMessages.roomId = chatRooms.id AND chatMessages.userId = userData.userId'); $qry->execute(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM