'Laravel Eloquent find rows with one common unknown field
I have one table
inbox
| inboxid | user_id |
| SDFHK2D | 123 |
| SDFHK2D | 124 |
| GGGFHK2 | 125 |
| GGGFHK2 | 126 |
What I want to fetch is:
Records which is common for both users from inbox table only. (AGAIN NO JOIN) Something like this
Select *
from inbox
where [ user_id = 123 , user_id = 124 ]
AND inboxid is COMMON
So basically I want to fetch all inbox id's which are common between user 123 and user 124
How can I do it with Laravel Eloquent or by simple SQL query?
Result Required
| inboxid | p_user_id | s_user_id |
| SDFHK2D | 123 | 124 |
Solution 1:[1]
Do a GROUP BY, use HAVING to make sure both 123 and 124 are there:
select inboxid, min(user_id) as p_user_id, max(user_id) as s_user_id
from inbox
where user_id in (123, 124)
group by inboxid
having count(distinct user_id) > 1
If you also want other pairs than 123/124 having the same inboxid, simply skip the WHERE clause.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jarlh |
