【问题标题】:Need query to find all records in Table1 that have multiple matches in Table2需要查询以查找 Table1 中与 Table2 中具有多个匹配项的所有记录
【发布时间】:2013-03-28 19:51:06
【问题描述】:

我有 2 个表,RequestAction 由字段 request_id 连接。

这是一个快速的数据示例:

Request
request_id    group
100           My Group Name
101           My Group Name
102           My Group Name

Action
request_id    action_id    username
100           10           JDOE
100           11           ASMITH
101           12           SMILLER
102           13           CBROWN

我需要获取所有请求的列表以及具有多个操作的 action_id 和用户名。这是我目前拥有的,但它列出了所有具有一个或多个操作的请求。

所以结果应该显示:

request_id    action_id    username
100           10           JDOE
100           11           ASMITH

以下可以选择我需要的内容,但我不确定如何将 request_id > 1 放入其中:

SELECT request.request_id, action.action_id, action.username
FROM request RIGHT JOIN action ON request.request_id = action.request_id
WHERE (((request.group)="My Group Name"))
GROUP BY request.request_id, action.action_id, action.username;

感谢您的帮助!

【问题讨论】:

  • 如果您添加 HAVING COUNT(Action.Request_id) > 1 是否可以满足您的需求?
  • 这给出了 0 个请求。我需要先选择 action.request_id 吗?

标签: sql ms-access


【解决方案1】:

怎么样:

SELECT 
Action.request_id, 
Action.action_id, Action.username
FROM [Action] 
INNER JOIN Request ON Action.request_id = Request.request_id
WHERE Action.request_id In (
  SELECT request_id FROM action Group By Request_Id 
  HAVING Count(request_id)>1)
AND Request.group="My Group Name"

【讨论】:

    【解决方案2】:

    我认为你只需要一个having 子句。这类似于 where 子句,但在聚合列上:

    SELECT request.request_id, action.action_id, action.username
    FROM request RIGHT JOIN
         action
         ON request.request_id = action.request_id
    WHERE (((request.group)="My Group Name"))
    GROUP BY request.request_id, action.action_id, action.username
    having counte(request.request_id) > 1
    

    【讨论】:

    • 应该countersCOUNT
    猜你喜欢
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2022-07-29
    • 1970-01-01
    • 2019-05-03
    • 2020-10-08
    相关资源
    最近更新 更多