MYSQL基于选择选择

时间:2011-09-10 18:10:30

标签: mysql

你的帮助将不胜感激...... 如果我有下表和示例数据... myGroupTable


group_Id:user_Id
1:3
1:7
1:100
2:3
2:7
2:100
2:104
4:42
4:98
4:13

我想要一个sql语句,它会...... 返回一个完全具有指定user_Id的group_Id。 例如......是否有group_Id具有User_Id的3,7和100 回答:group_id 1。 请注意,我不希望它返回group_Id 2,因为它的user_Id为104 ... 亲切的问候J

4 个答案:

答案 0 :(得分:2)

SELECT
    group_Id,
    SUM(
        IF user_Id = 3 THEN 1
        ELSEIF user_Id = 7 THEN 2
        ELSEIF user_Id = 100 THEN 4
        ELSE 8
    ) AS bits
FROM myGroupTable
GROUP BY group_Id
HAVING bits=7

这假设你不能为同一个group_Id拥有重复的user_Id,例如,这可能永远不会发生:

group     user
   1         3
   1         3

修改:您可以按以下方式构建查询:

<?php
$ids = array(3, 7, 100);
$power = 2;
$query = "
    SELECT
    group_Id,
    SUM(
        IF user_Id = " .$ids[0]. " THEN 1 ";
foreach ($id in $ids) { 
    $query .= " ELSEIF user_Id = $id THEN " . $power;
    $power = $power * 2;
}
$query .= " ELSE $power
    ) AS bits
    FROM myGroupTable
    GROUP BY group_Id
    HAVING bits = " . ($power - 1);

答案 1 :(得分:1)

这是另一种选择:

SELECT group_id, GROUP_CONCAT(user_id ORDER BY user_id) AS user_id_list
FROM group_user
GROUP BY group_id
HAVING user_id_list = '3,7,100'

答案 2 :(得分:0)

另一种解决方案:

SELECT group FROM tbl WHERE group_id NOT IN(SELECT DISTINCT group_id FROM tbl WHERE user_id NOT IN(3,7,100))AND user_id IN(3,7,100);

答案 3 :(得分:-1)

select group_id,
sum(
  case user_id in(3,7,100)
  when 1 then 1
  else -99
  end
) as must_be_3
from group_user
group by group_id
having must_be_3=3;