使用另一个表中的行过滤查询的输出

时间:2013-10-15 01:42:22

标签: mysql sql

我需要一些代码的帮助

我有两个名为“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

过滤结果

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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 ...我想要的东西!