-3

我需要一些代码方面的帮助

我有 2 个表,分别称为“stuff”和“something”,我有以下信息:

               stuff                                  something
+-------------+---------------------+    +-------------+---------------------+
| member_id   |     group_id        |    |  group_id   |      some_id        |
+-------------+---------------------+    +-------------+---------------------+
|      11     |         aa          |    |      aa     |         7           |
|      11     |         bb          |    |      dd     |         8           |
|      22     |         bb          |    |      bb     |         9           |
|      11     |         cc          |    +-------------+---------------------+
|      22     |         cc          |
|      33     |         cc          |
|      11     |         dd          |
+-------------+---------------------+

这个查询:

SELECT  group_id
FROM    stuff a
WHERE   member_id IN (11)  -- <<== list of member_id (can be 11,22 or 22,33 or 11,22,33)
    AND
    EXISTS
    (
      SELECT group_id
      FROM stuff b
      WHERE a.group_id = b.group_id
      GROUP BY group_id
      HAVING COUNT(*) = 1                   -- <<== number of member_id
    )
GROUP   BY group_id
HAVING  COUNT(*) = 1                            -- <<== number of member_id

将返回aadd

我的问题是:如果是,我该如何过滤结果some_id=7

4

3 回答 3

2

你的问题比较混乱。似乎一个简单的JOIN应该工作:

SELECT s.group_id
FROM stuff s 
    INNER JOIN something so ON s.group_id = so.group_id 
WHERE s.member_id = 11 AND
    so.some_id = 7
于 2013-10-15T01:48:21.300 回答
2

这对我来说看起来很奇怪......

试试这个:

SELECT * //or whatever
FROM stuff 
JOIN something ON stuff.group_id=something.group_id 
WHERE something.some_id=7 AND stuff.member_id IN (11);

这将返回:

member_id    |    group_id    |    some_id    |
-----------------------------------------------
    11              aa                7
于 2013-10-15T01:51:10.367 回答
0
SELECT  `group_id`
FROM    `stuff` a
WHERE   `member_id` IN (11) -- <<== list of member_id (can be 11,22 or 22,33 or 11,22,33)
AND
EXISTS
(
    SELECT  `group_id`
    FROM    `stuff` b
    WHERE a.`group_id` = b.`group_id`
    AND
    EXISTS
    (
        SELECT  c.`group_id`
        FROM      `something` c
        WHERE   c.`group_id` = b.`group_id`
        AND     c.`some_id`=7                        -- <<== number of some_id=7
    )  
    GROUP BY `group_id`
    HAVING COUNT(*) = 1               -- <<== number of member_id
)
GROUP   BY `group_id`
HAVING  COUNT(*) =1               -- <<== number of member_id

这将返回aa......我想要的!

于 2013-10-16T20:06:31.980 回答