0

假设我有以下元素:

动作表

id          type        date
----------- ----------  ----------
1           start       2012-01-01 10:00:00
2           suspend     2012-01-01 11:00:00
3           resume      2012-01-01 12:00:00
4           suspend     2012-01-01 13:00:00
5           resume      2012-01-01 14:00:00
6           stop        2012-01-01 15:00:00
7           refill      2012-01-01 16:00:00
8           stop        2012-01-01 17:00:00

关联表

id    actionID    elementID
----- ----------- -----------
1     1           1
2     2           1
3     3           1
4     4           1
5     5           1
6     6           1
7     7           1
8     8           1

元素表

id    name
----- -----------
1     my element

所以基本上我有一个元素,它的状态根据一些用户触发的动作(动作表)而演变,这些动作可以通过许多元素共享(这就是我有一个关联表的原因)。

我想在 SQL 查询中检索它:

ElementID,开始动作 ID,最后动作 ID(开始动作总是链接到一个元素)

是否可以不编写多个 sql 查询?我正在寻找性能最高的查询,因为它将在具有数百万个条目的表上运行(关联表和操作表)

谢谢

4

2 回答 2

2
select last.elementID, start.actionID as startAction, last.actionID as lastAction
from (
    select elementID, max(actionID) as actionID
    from Association
    group by elementID
    ) last
inner join (
    select elementID, min(actionID) as actionID
    from Association
    group by elementID
    ) start on start.elementID = last.elementID
于 2012-09-20T14:33:38.047 回答
1
SELECT e.Id, e.name,
  MAX(CASE WHEN a.type = 'start' THEN a.actiondate END) AS 'StartAction',
  MAX(CASE WHEN a.type = 'stop' THEN a.actiondate END) AS 'ENDAction'
FROM @actions a 
INNER JOIN @association s ON a.Id = s.actionid
INNER JOIN @elements e ON s.id = e.Id
GROUP BY e.id, e.name
于 2012-09-20T14:25:21.337 回答