加入发件人和收件人的用户名和邮件信息

时间:2016-07-04 10:02:54

标签: mysql sql

我在PHP / MySQL中做了一个小型用户/消息传递脚本作为学习练习。当我执行查询以显示消息时,我还想从发送方和接收方输出user_username。这就是我到目前为止所做的:

  SELECT
    messages.*,
    user_receiver.user_username as message_receiver_username,
    user_sender.user_username as message_sender_username
  FROM
    messages
  INNER JOIN
    users user_receiver ON messages.message_receiver = user_receiver.user_id
   INNER JOIN
    users user_sender ON messages.message_sender = user_sender.user_id

SQL小提琴代码:http://sqlfiddle.com/#!9/5686aa/6

问题是这个SQL代码将用户名返回为" user_username"两次。 我想将用户名返回为" message_receiver_username"和" message_sender_username"。

新信息:似乎查询在phpMyAdmin中工作正常,并且它是SQL Fiddle返回原始用户表头(user_username)而不是message_sender_username和message_receiver_username。我做错了什么导致不同系统的结果不同?或者查询是否正确且SQL Fiddle错误?

以下是数据库中的一些示例内容,只是为了让您更好地了解:

|-------------------------------|
| users                         |
|-------------------------------|
| user_id | user_username | ... |
|---------|---------------|-----|
| 1       | Max           |     |
| 2       | Maxim         |     |
| 3       | Maxim2        |     |
| ...     | ...           |     |
|-------------------------------|

|-------------------------------------------------------------|
| messages                                                    |
|-------------------------------------------------------------|
| message_id  | ... | message_sender  | message_receiver  |...|
|-------------|-----|-----------------|-------------------|---|
| 1           |     | 1               | 2                 |   |
| 2           |     | 1               | 2                 |   |
| 3           |     | 2               | 3                 |   |
| ...         |     | ...             | ...               |   |
|-------------------------------------------------------------|

1 个答案:

答案 0 :(得分:0)

你应该写

     SELECT
    messages.*,
    user_receiver.user_username as 'message_receiver_username',
    user_sender.user_username as 'message_sender_username'
  FROM
    messages
  INNER JOIN
    users user_receiver ON messages.message_receiver = user_receiver.user_id
   INNER JOIN
    users user_sender ON messages.message_sender = user_sender.user_id

这将解决您的问题