1

我需要从成员表中选择 2 行来获取名称和 ID,并且我需要从消息表中获取所有行。到目前为止,这是我所拥有的任何提示或帮助,我们将不胜感激 EDIT Tables

会员 短信

 SELECT member_messages.message_to, 
       member_messages.message_from, 
       member_messages.message_time, 
       member_messages.message_body,
       members.display_name,members.id 
FROM members
INNER JOIN member_messages 
   ON member_messages.message_to = members.id  AS 'to'
INNER JOIN member_messages 
   ON member_messages.message_from = members.id AS 'from'
WHERE member_messages.message_to = '$userId'
4

2 回答 2

1

您的连接几乎是正确的,但您需要引用表别名to以及您在列表中的s 中from分配的别名,而不是直接引用。由于和都是MySQL 保留关键字,因此您必须将它们都反引号。JOINSELECTmembersTOFROM

SELECT member_messages.message_to, 
       member_messages.message_from, 
       member_messages.message_time, 
       member_messages.message_body,
       /* Select cols from both aliases of members, with column aliases */
       `to.display_name AS to_name,
       `to`.id AS to_id ,
       `from`.display_name AS from_name,
       `from`.id AS from_id 
/* First reference to members as `to` */
FROM members AS `to`
INNER JOIN member_messages 
   ON member_messages.message_to = `to`.id
/* Second reference to members as `from` */
INNER JOIN members AS `from` 
   ON member_messages.message_from = `from`.id
WHERE member_messages.message_to = '$userId'
于 2013-01-10T00:41:18.147 回答
0

如果将 db 结构放在这里会很有帮助。假设您的表 'member_messages' 包含您要阅读的所有消息,那么您需要将此表与您的 'members' 表连接两次以检索 'from' 和 'to' 成员的名称。

您可能正在寻找这样的东西:

SELECT
    message.message_time, message.message_body,
    member_to.id, member_to.display_name,
    member_from.id, member_from.display_name
FROM   
    member_messages AS message
JOIN   
    members AS member_to ON members.id = member_messages.message_to 
JOIN   
    members AS member_from ON members.id = members_messages.message_from

如果您的数据库系统中保留了某些单词,请更改它们。

于 2013-01-10T00:13:52.780 回答