Mysql 我的sql语句,用于在任何特定列值已从上一个条目更改时获取行
我有一个带有日期和表格条目的表格。我正在使用我的sql数据库Mysql 我的sql语句,用于在任何特定列值已从上一个条目更改时获取行,mysql,sql,Mysql,Sql,我有一个带有日期和表格条目的表格。我正在使用我的sql数据库 Table employees updatedDate req_count error_count 14-03-2014 10:20:39 1 0 15-03-2014 11:10:00 1 0 15-03-2014 12:10:00 1 1 15-03-201
Table employees
updatedDate req_count error_count
14-03-2014 10:20:39 1 0
15-03-2014 11:10:00 1 0
15-03-2014 12:10:00 1 1
15-03-2014 16:12:00 1 1
16-03-2014 12:09:00 2 10
如果与以前的条目有任何更改,我将获取条目。
例如,sql查询应该只返回req\u count和error\u count的更改条目
updatedDate req_count error_count
14-03-2014 10:20:39 1 0
15-03-2014 12:10:00 1 1
16-03-2014 12:09:00 2 10
我正在使用
SELECT updateDate,req_count,error_count FROM employees WHERE empId=10
AND req_count > 0 OR error_count > 0
这将返回所有5行,因为我只需要3行。如果某个特定的列值发生了更改,那么获取行的正确方法是什么。我的建议。获取每个员工的上次更新日期。然后连接回表以获取上一条记录,以便进行比较。以下是获取上次更新日期的一种方法:
select e.*,
(select max(e2.updatedDate)
from employees e2
where e2.empId = e.empId and e2.updatedDate < e.updatedDate
) as prev_updatedDate
from employees;
那么完整的查询是:
select e.*
from (select e.*,
(select max(e2.updatedDate)
from employees e2
where e2.empId = e.empId and e2.updatedDate < e.updatedDate
) as prev_updatedDate
from employees
) e left join
employees prev_e
on prev_e.empId = e.empId and prev_e.updatedDate = e.prev_updatedDate
where (prev_e.empId is null) or
(prev_e.req_count <> e.req_count or prev_e.error_count <> e.error_count);
你可以试试这个
SELECT a.*
FROM employees AS a
WHERE
empId=10
AND
(
(
a.req_count <> (
SELECT
b.req_count
FROM
employees AS b
WHERE
a.id > b.id
ORDER BY
b.id DESC
LIMIT 1
)
)
OR (
a.error_count <> (
SELECT
b.error_count
FROM
employees AS b
WHERE
a.id > b.id
ORDER BY
b.id DESC
LIMIT 1
)
)
)
查询在记录上运行,并针对每个记录检查req_计数或error_计数是否已从上一条记录更改,其中它通过一个名为id的字段获取上一条记录,我不确定您的表中是否有该字段