Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL select based on the selects

Tags:

mysql

You're help would be much appreciated... If I have the following table and sample data... 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

I would like a sql statement that would... Return a group_Id that has exactly the specified user_Id's in them. eg... is there a group_Id that has User_Id's 3, 7 and 100 answer: group_id 1. Please note that I dont want it to return a group_Id 2, as that also has a user_Id of 104 in it... Kind regards J

like image 290
jon Avatar asked Apr 01 '26 21:04

jon


2 Answers

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

This assumes that you cannot have duplicate user_Ids for the same group_Id, eg this could never happens:

group     user
   1         3
   1         3

Edit: You can build your query in the following way:

<?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);
like image 104
Robert Martin Avatar answered Apr 03 '26 11:04

Robert Martin


Here's another alternative:

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'
like image 24
Bill Karwin Avatar answered Apr 03 '26 12:04

Bill Karwin