MySQL How to select multiple rows with WHERE multiple columns on the same table?

Viewed 928

I want to select room_id based on column user_id and del

room_id user_id del
1 23 0
1 45 0
1 56 1
25 23 0
25 45 0
25 56 0

This is an example of my table, and I want to select room_id WHERE:

"user_id = 23 AND del = 0" (del of the row where user_id=23) 

AND

"user_id = 45 AND del = 0" (del of the row where user_id=45) 

AND

"user_id = 56 AND del = 0" (del of the row where user_id=56) 

The query should only return room_id = 25 How do I achieve this with PHP or CodeIgniter?

I have tried using this and it's not working:

$this->db->select()
->from('table')
->where(['user_id' => 23, 'del' => 0])
->where(['user_id' => 45, 'del' => 0])
->where(['user_id' => 56, 'del' => 0])
->get()->result_array();

*Notes: it worked when I tried using join tables on the same table, but when I have 10 user_id (joining the same table 10 times), the query runs super slow (because it is a big table with almost close to a million rows).

Thank you in advance.

6 Answers

Use a where clause to filter matching rows, then group the results and add a having clause:

SELECT room_id
FROM t
WHERE (user_id = 23 AND del = 0)
OR    (user_id = 45 AND del = 0)
OR    (user_id = 56 AND del = 0)
GROUP BY room_id
HAVING COUNT(*) = 3 -- there are three rows with matching condition for that room

You can try like this

SELECT room_id
FROM table
WHERE user_id = 23 AND del = 0 AND user_id = 45 AND del = 0 AND user_id = 56 AND del = 0;

Then the query may look like this

$this->db->select('room_id')
->from('table')
->where(['user_id' => 23, 'del' => 0])
->orWhere(['user_id' => 45, 'del' => 0])
->orWhere(['user_id' => 56, 'del' => 0])
->get()->result_array();

You can either put all your user_ids in parentheses:

SELECT room_id
FROM table
WHERE (user_id = 23 OR user_id = 45 OR user_id = 56) AND del = 0;

or you can user the WHERE IN clause:

SELECT room_id
FROM table
WHERE user_id IN (23, 45, 56) AND del = 0;

"user_id = 23 AND del = 0" will add the Room ID 1 to the result set as well. Add a condition for room_id = 25 in the where clause.

SELECT room_id
FROM
(
SELECT `room_id`,`user_id`,`del`,GROUP_CONCAT(user_id ORDER BY user_id ASC) ordered_user
FROM    `my_table`
GROUP BY room_id,del
HAVING ordered_user = "23,45,56" AND del=0
)
AS dbx

Explaination:

Your Data:

This is Your Data

Group by Room_id and Del After that filter by HAVING in ordered_user After filter by having

Make New dummy for only return 25

Optional Step

Related