通过JOIN获取有关两个用户的信息

时间:2016-04-22 17:45:58

标签: php mysql

我遇到了问题。我现在正在建立一个私人消息系统,我需要获取用户及其排名信息以在屏幕上打印它。所以我做JOIN

SELECT 
   private_messages.from    as `from`,
   private_messages.to      as `to`,
   private_messages.theme   as `theme`,
   private_messages.date    as `date`,
   private_messages.message as `message`,
   users.username           as `username`,
   users.id                 as `user_id`,
   private_messages.id      as `pm_id`,
   ranks.style              as `style`,
   ranks.rank_name          as `rank_name`
FROM `private_messages` 
LEFT JOIN `users` ON private_messages.from = users.id
LEFT JOIN `ranks` ON users.rank            = ranks.id
WHERE   private_messages.id=? LIMIT 1

但问题是我只收到有关用户'的信息。 (谁发送了一条消息)并且没有获得关于用户的等级和其他信息。 (收到消息的人)我也需要他的信息而且不知道该怎么做,任何人都可以帮助我吗? :)

1 个答案:

答案 0 :(得分:1)

如果你想要关于两个用户,你必须加入两次表用户一个用户user_from一个用户user_to ...

这只是获取两个用户信息的建议

SELECT 
    private_messages.from as `from`,
    private_messages.to as `to`,
    private_messages.theme as `theme`,
    private_messages.date as `date`,
    private_messages.message as `message`,
    users.username as `username`,
    users_to.username as `username_to`
    users.id as `user_id`,
    private_messages.id as `pm_id`,
    ranks.style as `style`,
    ranks.rank_name as `rank_name`
    FROM `private_messages` 
    INNER JOIN `users` ON private_messages.from = users.id
    INNER JOIN `users` as user_to ON private_messages.to = users.id
    LEFT JOIN `ranks` ON users.rank = ranks.id
    WHERE   private_messages.id=? LIMIT 1