I am building a mysql based chat application.
My database schema has the following tables,
Users Messages
================= =================
id id
screen_name message
from
to
timestamp
The from and to fields on the messages table contain the id's of the users that sent and received each message.
I am trying to display all messages between a user ($id) and one of their friends ($friend). My query is the following:
$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 )";
The problem is that every message is twice in the result table.
I tried using DISTINCT but it either doesn't work in this scenario or I used it wrong.
What should my query be in order to have each message between the two users only once?
Something like this should do the trick:
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)
What this does is joing the "users" table twice, once on the "to" column and the second time on the "from" column.
@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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.