Jump to content

Recommended Posts

I am at a loss here guys. Please see if you can help me put this query together.

 

I have a table called messages.

 

CREATE TABLE  `db.app`.`messages` (
`id` INT( 32 ) NOT NULL AUTO_INCREMENT ,
`sender` VARCHAR( 64 ) NOT NULL ,
`recipient` VARCHAR( 64 ) NOT NULL ,
`body` TEXT NOT NULL ,
`timestamp` INT( 32 ) NOT NULL ,
PRIMARY KEY (  `id` )
) ENGINE = MYISAM ;

 

And a table called users.

 

 

CREATE TABLE  `db.app`.`users` (
`id` INT( 32 ) NOT NULL AUTO_INCREMENT ,
`nickname` VARCHAR( 64 ) NOT NULL ,
PRIMARY KEY (  `id` )
) ENGINE = MYISAM ;

 

When a message is made, it inserts the ID of the sender into `messages`.`sender`, the ID of the recipient into `messages`.`recipient`, the message body, and UNIX timestamp. This is working fine.

 

My problem lies with getting a list of all the unique conversations. (Like text messages on iPhones).

 

so if we have data like so...

 

messages table

id | sender | recipient | body | timestamp

1  | 1234 | 5678 | testing message | 1290233086

2  | 5678 | 1234 | testing reply | 1290233089

 

users table

id | nickname

1234 | john

5678 | peter

 

I would like to be able to generate query results like so...

results

other_person_id | other_person_nickname | last_message | last_message_timestamp

1234, john, testing reply, 1290233089

 

For the life of me, I cant figure out this query....

 

Link to comment
https://forums.phpfreaks.com/topic/219412-cannot-come-up-with-mysql-query/
Share on other sites

select a.recipient, b.nickname, a.body, a.timestamp

from messages a

join users b on (a.recipient = b.id)

where a.recipient = 1234

 

I would also change recipient and sender to INT and not varchar, since they are in fact your other IDs.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.