1

我正在构建一个基于 mysql 的聊天应用程序。

我的数据库架构有以下表格,

       Users               Messages
   =================   =================
        id                 id
        screen_name        message
                           from
                           to
                           timestamp

消息表上的 from 和 to 字段包含发送和接收每条消息的用户的 ID。

我正在尝试显示用户 ($id) 和他们的一位朋友 ($friend) 之间的所有消息。我的查询如下:

$query = "SELECT messages.* , users.screen_name FROM users CROSS JOIN messages ";
$query .= "ON ( messages.to = $id AND messages.from = $friend ) ";
$query .= "OR ( messages.to = $friend AND messages.from = $id )";

问题是每条消息在结果表中都有两次。

我尝试使用 DISTINCT,但在这种情况下它要么不起作用,要么我用错了。

为了让两个用户之间的每条消息只有一次,我的查询应该是什么?

4

2 回答 2

3

这样的事情应该可以解决问题:

SELECT
  messages.*,
  users_from.screen_name AS from_screen_name,
  users_to.screen_name AS to_screen_name
FROM
  messages
    JOIN users AS users_from ON messages.from = users_from.id
    JOIN users AS users_to ON messages.to = users_to.id
WHERE
  (messages.to = $id AND messages.from = $friend)
  OR ( messages.to = $friend AND messages.from = $id)

这样做是将“users”表连接两次,一次在“to”列上,第二次在“from”列上。

于 2012-04-10T13:31:52.630 回答
1

@Travesty3 has already suggested that the DISTINCT keyword will only exclude duplicate rows where all fields are equal to another row. Therefore, the DISTINCT keyword is not the way to go here.

What you can do, however, is to simply GROUP BY messages.id in order to get only one row per message ID (there is no guarantee, however, as to which of the two rows will be excluded).

于 2012-04-10T13:45:14.167 回答