我需要从成员表中选择2行来获取名称和ID,我需要从消息表中获取所有行。这是我到目前为止任何提示或帮助表示赞赏 编辑 表
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'
答案 0 :(得分:1)
您的联接几乎是正确的,但您需要引用您在to
列表中的from
中指定的表别名JOIN
和SELECT
,而不是而不是直接提到members
。由于TO
和FROM
都是MySQL reserved keywords,因此您必须同时引用它们。
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'
答案 1 :(得分: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
如果您的数据库系统中保留了某些单词,请更改它们。