基于几个条件的递归表连接

时间:2014-12-22 07:17:42

标签: sql recursion

我的系统中有以下审核表:

+---+----------------+-------------+----------------+-----------------------+-----------+
|ID |field           |checkpoint   |value1          |value2                 |created_by |
+---+----------------+-------------+----------------+-----------------------+-----------+
|1  |active          |0            |null            |1                      |user1      |
|2  |person          |0            |null            |jonh                   |user1      |
|4  |duration        |2            |01.01.1970 0:00 |01.01.1970 0:07        |user1      |
|2  |field_update    |1            |0               |1                      |user2      |
|1  |opened_by       |1            |null            |sam                    |user1      |
|2  |work_note       |2            |null            |TEST                   |user2      |
+---+----------------+-------------+----------------+-----------------------+-----------+

具有相同ID的值是指一个实体。此审计表跟踪一个实体内的所有更改。所以我需要抓住以下实体: 当field ='person'和value2 ='john'时,我需要获得该实体的下一次更新(ID)。在表上看它是第4行(相同的ID和检查点=检查点+ 1)。因此,我们需要通过此ID和created_by字段计算具有所述条件的所有ID。

2 个答案:

答案 0 :(得分:0)

怎么样?

SELECT      *
FROM        mytable a 
INNER JOIN  mytable b ON a.ID = b.ID
WHERE       a.field = 'person'
AND         a.value2 = 'john'
AND         b.checkpoint = a.checkpoint + 1

答案 1 :(得分:0)

你想要这个吗?

Select count(id) from audit where id = (select id from audit
group by id 
having count(distinct checkpoint)=max(checkpoint) and min(checkpoint)=1 
where field = 'person' AND value2 = 'john')
相关问题