Peter
Peter

Reputation: 1931

SQL Query Inner Join and OR

How do i select using INNER JOIN and OR, i tried using below query but it doesn't return anything also no error

SELECT * FROM chatroom_message cm
INNER JOIN users_account ua
ON cm.userid_a = ua.reg_userid 
OR cm.userid_b = ua.reg_userid 
WHERE cm.userid_a = :chat_client OR cm.userid_b = :chat_client

Upvotes: 4

Views: 373

Answers (4)

Thorsten Kettner
Thorsten Kettner

Reputation: 94914

Let's say :chat_client = 123. Then you'd select all chatroom_message records where userid_a = 123 plus all chatroom_message records where userid_b = 123.

userid_a  userid_b
111       222         <- this one not
333       123         <- this one yes
123       444         <- this one yes

To these records you join users_account. This gets you:

userid_a  userid_b  username
333       123       Mr. 333
333       123       Mr. 123
123       444       Mr. 123
123       444       Mr. 444

So if you don't get any records, then there simply is no chatroom_message record for user 123 (or there is no matching entry in users_account which should be impossible due to foreign key constraints.

The query is fine. Check your parameter and data.

Upvotes: 0

Peace_Man
Peace_Man

Reputation: 45

You will need two inner joins for this to work -- One for userid_a and another for userid_b.

Upvotes: 0

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23078

Igor's answer is the straightforward way, but I am thinking of getting rid of OR which is usually associated with poorer performance and UNION the results for each reg_userid. Something like the following:

SELECT * FROM chatroom_message cm
INNER JOIN users_account ua ON cm.userid_a = ua.reg_userid 
WHERE cm.userid_a = :chat_client
UNION ALL
SELECT * FROM chatroom_message cm
INNER JOIN users_account ua ON cm.userid_b = ua.reg_userid 
WHERE cm.userid_b = :chat_client

Although this might be faster, the data for a specific chatroom_message is slightly harder to get, as it is split between 2 records. It depends on what you are doing with this data afterwards.

Upvotes: 3

Igor
Igor

Reputation: 62213

SELECT * 
FROM chatroom_message cm INNER JOIN users_account ua ON cm.userid_a = ua.reg_userid 
INNER JOIN users_account ub ON cm.userid_b = ub.reg_userid 
WHERE cm.userid_a = :chat_client OR cm.userid_b = :chat_client

The change here is 2 joins, one join per user on the user table. This is because you have 2 user ids in the message table that are different (no one chats to themselves) so you need a join for userid_a and another join for userid_b.

The join you had was effectively returning 0 records because userid_a will never equal userid_b. Also you do not want an OR in your WHERE clause for this query.

The WHERE clause was fine.

Upvotes: 4

Related Questions