Jon*_*hon 3 mysql sql greatest-n-per-group
我有两个表 - 一个叫customer_records,另一个叫customer_actions.
customer_records 具有以下架构:
CustomerID (auto increment, primary key)
CustomerName
...etc...
Run Code Online (Sandbox Code Playgroud)
customer_actions 具有以下架构:
ActionID (auto increment, primary key)
CustomerID (relates to customer_records)
ActionType
ActionTime (UNIX time stamp that the entry was made)
Note (TEXT type)
Run Code Online (Sandbox Code Playgroud)
每次用户对客户记录执行操作时,都会输入一个条目customer_actions,并且用户有机会输入一个注释.ActionType可以是少数几个值之一(如'设计更新'或'添加案例信息' - 只能是选项列表中的一个).
我希望能够做的是显示customer_records最后ActionType一个特定值的记录列表.
到目前为止,我已经搜索了网/ SO并想出了这个怪物:
SELECT * FROM (
SELECT * FROM (
SELECT * FROM `customer_actions` ORDER BY `EntryID` DESC
) list1 GROUP BY `CustomerID`
) list2 WHERE `ActionType`='whatever' LIMIT 0,30
Run Code Online (Sandbox Code Playgroud)
这很棒 - 它列出了每个客户ID及其最后一个操作.但有时候查询速度非常慢(注意:有近20,000条记录customer_records).任何人都可以提供任何关于我如何对这个查询怪物进行排序或调整我的表以提供更快结果的提示?我正在使用MySQL.非常感谢任何帮助,谢谢.
编辑:要清楚,我需要查看最后一次操作的客户列表是"什么".
要按客户的上一个操作过滤客户,您可以使用相关的子查询...
SELECT
*
FROM
customer_records
INNER JOIN
customer_actions
ON customer_actions.CustomerID = customer_records.CustomerID
AND customer_actions.ActionDate = (
SELECT
MAX(ActionDate)
FROM
customer_actions AS lookup
WHERE
CustomerID = customer_records.CustomerID
)
WHERE
customer_actions.ActionType = 'Whatever'
Run Code Online (Sandbox Code Playgroud)
您可能会发现避免相关子查询更有效,如下所示......
SELECT
*
FROM
customer_records
INNER JOIN
(SELECT CustomerID, MAX(ActionDate) AS ActionDate FROM customer_actions GROUP BY CustomerID) AS last_action
ON customer_records.CustomerID = last_action.CustomerID
INNER JOIN
customer_actions
ON customer_actions.CustomerID = last_action.CustomerID
AND customer_actions.ActionDate = last_action.ActionDate
WHERE
customer_actions.ActionType = 'Whatever'
Run Code Online (Sandbox Code Playgroud)