在MySQL中选择子查询(带有ANY和IN的子查询)

时间:2009-03-04 20:43:33

标签: mysql mysql-error-1242

感谢您的答案!

了解更多信息


这很难解释,所以让我们设置舞台......

userActions         userGroupMap
+------+--------+   +------+-------+
| user | action |   | user | group |
+------+--------+   +------+-------+
| x    | acted! |   | x    | a     |
| y    | acted! |   | y    | a     |
| y    | acted! |   | z    | b     |
| z    | acted! |   +------+-------+
| y    | acted! |
| z    | acted! |
| x    | acted! |
| z    | acted! |
+------+--------+

我想选择a组的动作。我的想法是

SELECT actions, user FROM userActions
    WHERE user = (SELECT user, group FROM userGroupMap WHERE group = a)

但显然这个子查询返回多行。我应该使用JOIN吗?

Subquery returns more than 1 row

6 个答案:

答案 0 :(得分:3)

一种方法是:

SELECT actions,
       user
FROM   userActions
WHERE  user IN
               (SELECT user
               FROM    userGroupMap
               WHERE   [group] = 'a'
               );

但是,对于大型表,此查询往往效率低下并且更好地进行连接:

SELECT actions,
       userActions.user
FROM   userActions
       INNER JOIN
              (SELECT user
              FROM    userGroupMap
              WHERE   [group] = 'a'
              ) AS tmp
       ON     userActions.user = tmp.user;

或者,正如乔纳森所提到的那样,你可以做到这一点,而且效率非常高,如果不是更多的话:

SELECT actions,
       userActions.user
FROM   userActions
       INNER JOIN userGroupMap
       ON     userActions.user = userGroupMap.user
WHERE  [group] = 'a';

答案 1 :(得分:1)

SELECT actions, user FROM userActions
    WHERE user IN (SELECT user FROM userGroupMap WHERE group = a)

SELECT actions, user FROM userActions
    WHERE user = ANY (SELECT user FROM userGroupMap WHERE group = a)

(修订:如其他人所述,只应退回用户专栏。)

答案 2 :(得分:1)

难道你不能做这样的事情:

SELECT 
  a.actions, 
  a.user 
FROM 
  userActions a 
  INNER JOIN userGroupMap g 
    ON a.user = g.user
WHERE
  g.group = 'a'

答案 3 :(得分:1)

实际上,此查询将为您提供所需内容:

SELECT actions, user 
FROM userActions 
WHERE user IN 
    (SELECT user FROM userGroupMap WHERE group = 'a')

答案 4 :(得分:0)

SELECT actions, user FROM userActions
    WHERE user = (SELECT user FROM userGroupMap WHERE group = a)

子查询返回用户和组(两个​​字段)时应该只返回用户。

答案 5 :(得分:0)

而是使用join而不是子查询:

SELECT
    userActions.action,
    userActions.user
FROM
    userActions
CROSS JOIN userGroupMap ON 
    userGroupMap.user = userActions.user AND
    userGroupMap.group = 'a'