I have the following table
id group_id user_id
1 2 11
2 2 12
3 2 13
4 3 11
5 3 12
6 4 11
Now I want the common group IDs Means if
I pass user_id (11,12) then result will be group_id (2 and 3)
I pass user_id (11) then result will be group_id (2,3 and 4)
I pass user_id (11,12,13) then result will be group_id (2)
I pass user_id (13,15) then result will be zero group_id (NULL)
I am working with CodeIgniter but you can suggestion me in core SQL. It would be good if your answer is in CI model(query) standard.
You can use distinct
and where_in
to get your desire result. Where array
contain your user_id
$this->db->distinct();
$this->db->select('group_id');
$this->db->from('your_table');
$this->db->where_in('user_id',array('11','12');//you can pass here 11,12,13 or 11 or 11,12
For And Condition
$array = array('user_id' => 11, 'user_id' => 12);
$this->db->distinct();
$this->db->select('group_id');
$this->db->from('your_table');
$this->db->where($array);
One way to do it is to use the NATURAL JOIN of SQL.
For user_id = 11
SELECT group_id FROM table_name WHERE user_id = 11;
For user_id = 11,12
SELECT group_id FROM
(SELECT group_id FROM table_name WHERE user_id = 11) t1
NATURAL JOIN
(SELECT group_id FROM table_name WHERE user_id = 12) t2;
For user_id = 11,12,13
SELECT group_id FROM
(SELECT group_id FROM table_name WHERE user_id = 11) t1
NATURAL JOIN
(SELECT group_id FROM table_name WHERE user_id = 12) t2
NATURAL JOIN
(SELECT group_id FROM table_name WHERE user_id = 13) t3;
SELECT *, group_concat(DISTINCT(group_id)) FROM test_temp WHERE user_id IN(11,12)