Scarface
Scarface

Reputation: 3913

Need help with query

I have the following table. It stores messages that each user has sent and received in chats. I want to select all the messages that a user has sent and received and retrieve them. I can then sort them by their conversation id in JQUERY. Would I have to do two queries for this or can I embed a query? Essentially what I want to do is

SELECT * FROM chatbox WHERE sender=? 
and 
SELECT * FROM chatbox WHERE receiver=?

I just want to try to avoid having two queries and two while loops for the results. Anyone have any suggestions?

Upvotes: 3

Views: 99

Answers (4)

Alex K.
Alex K.

Reputation: 175748

You can do it in a single query along with the sorting;

SELECT * FROM chatbox WHERE 'username' IN (sender, receiver) ORDER BY id

Upvotes: 2

Alex
Alex

Reputation: 3079

You can do it like this, and also do the ordering with MySQL too:

SELECT *
FROM chatbox
WHERE
  sender="<id>" OR
  receiver="<id>"
ORDER BY conversation_id

Upvotes: 3

CristiC
CristiC

Reputation: 22698

SELECT 
  *
FROM 
  chatbox
WHERE
  sender=? or receiver=?

Upvotes: 1

ADW
ADW

Reputation: 4070

SELECT * FROM chatbox WHERE sender=? OR receiver=?

Upvotes: 1

Related Questions