简体   繁体   中英

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
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.

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.

您需要两个内连接才能工作 - 一个用于userid_a,另一个用于userid_b。

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM