2

感谢您的精彩回答!

了解更多信息


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

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
4

6 回答 6

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;

或者,正如 Jonathon 所提到的,你可以做到这一点,并且它几乎同样有效,如果不是更多的话:

SELECT actions,
       userActions.user
FROM   userActions
       INNER JOIN userGroupMap
       ON     userActions.user = userGroupMap.user
WHERE  [group] = 'a';
于 2009-03-04T21:01:43.963 回答
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)

(修改:如其他人所述,仅应返回用户列。)

于 2009-03-04T20:50:24.817 回答
1

你不能做类似的事情:

SELECT 
  a.actions, 
  a.user 
FROM 
  userActions a 
  INNER JOIN userGroupMap g 
    ON a.user = g.user
WHERE
  g.group = 'a'
于 2009-03-04T20:51:27.123 回答
1

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

SELECT actions, user 
FROM userActions 
WHERE user IN 
    (SELECT user FROM userGroupMap WHERE group = 'a')
于 2009-03-04T20:56:34.397 回答
0
SELECT actions, user FROM userActions
    WHERE user = (SELECT user FROM userGroupMap WHERE group = a)

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

于 2009-03-04T20:49:23.090 回答
0

而不是使用连接而不是子查询:

SELECT
    userActions.action,
    userActions.user
FROM
    userActions
CROSS JOIN userGroupMap ON 
    userGroupMap.user = userActions.user AND
    userGroupMap.group = 'a'
于 2009-03-04T21:00:50.830 回答