MySQL通过匹配它们的id来组合两个表字段

Raj*_*nth 0 php mysql sql

例如,我创建了两个表.

表一:t5zgu_property_message

msg_from msg_to subject message

57       42     xxxxx   xxxxxx
57       42     xxxxx   xxxxxx
57       42     xxxxx   xxxxxx
42       42     xxxxx   xxxxxx
Run Code Online (Sandbox Code Playgroud)

表二:t5zgu_users

id username

42 Jack
57 Rocky
Run Code Online (Sandbox Code Playgroud)

我希望输出像这样:

msg_from msg_to subject message msg_from  msg_to

57       42     xxxxx   xxxxxx  Rocky     Jack
57       42     xxxxx   xxxxxx  Rocky     Jack
57       42     xxxxx   xxxxxx  Rocky     Jack
42       42     xxxxx   xxxxxx  Jack      Jack
Run Code Online (Sandbox Code Playgroud)

我目前的查询是:

SELECT 
    t5zgu_property_message.id,
        t5zgu_property_message.msg_from,
        t5zgu_property_message.msg_to,
        t5zgu_property_message.subject,
        t5zgu_property_message.message,
        t5zgu_users.username as msg_from
FROM 
    t5zgu_property_message,
        t5zgu_users
WHERE
    t5zgu_property_message.msg_from = t5zgu_users.id

ORDER BY t5zgu_property_message.id DESC
Run Code Online (Sandbox Code Playgroud)

这个查询与msg_from完美配合并获得正确的输出,但我不知道如何为msg_to编写.

任何想法或建议?谢谢.

Ale*_*s G 5

您只需要users再次加入表格:

SELECT 
    t5zgu_property_message.id,
        t5zgu_property_message.msg_from,
        t5zgu_property_message.msg_to,
        t5zgu_property_message.subject,
        t5zgu_property_message.message,
        t5zgu_users.username as msg_from,
        t5zgu_users2.username as msg_to
FROM 
    t5zgu_property_message,
    t5zgu_users,
    t5zgu_users t5zgu_users2
WHERE
    t5zgu_property_message.msg_from = t5zgu_users.id
    AND
    t5zgu_property_message.msg_to = t5zgu_users2.id

ORDER BY t5zgu_property_message.id DESC
Run Code Online (Sandbox Code Playgroud)

或者使用JOIN语法相同的东西:

SELECT 
    t5zgu_property_message.id,
        t5zgu_property_message.msg_from,
        t5zgu_property_message.msg_to,
        t5zgu_property_message.subject,
        t5zgu_property_message.message,
        t5zgu_users.username as msg_from,
        t5zgu_users2.username as msg_to
FROM 
    t5zgu_property_message
    JOIN t5zgu_users ON t5zgu_property_message.msg_from = t5zgu_users.id
    JOIN t5zgu_users t5zgu_users2 ON t5zgu_property_message.msg_to = t5zgu_users2.id
ORDER BY t5zgu_property_message.id DESC
Run Code Online (Sandbox Code Playgroud)