我有下表
id group_id user_id
1 2 11
2 2 12
3 2 13
4 3 11
5 3 12
6 4 11
现在我想要公共组ID意味着
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)
我正在使用CodeIgniter但您可以在核心SQL中建议我。如果您的答案是CI模型(查询)标准,那将是件好事。
答案 0 :(得分:1)
您可以使用distinct
和where_in
来获得您的愿望结果。 array
包含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);
答案 1 :(得分:0)
SELECT *, group_concat(DISTINCT(group_id)) FROM test_temp WHERE user_id IN(11,12)
答案 2 :(得分:-1)
一种方法是使用SQL的NATURAL JOIN。
对于user_id = 11
SELECT group_id FROM table_name WHERE user_id = 11;
对于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;
对于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;