MYSQL:选择已更改的行位置

时间:2013-06-13 08:14:54

标签: mysql sql

1 -

create table changes(snapdate date,value int, uid int); 
insert into changes values 
('2013-04-22', 0, 1 ), 
('2013-04-21', 1,1 ), 
('2013-04-20', 1,1 ), 
('2013-04-19', 1,1 ), 
('2013-04-19', 0,2 ), 
('2013-04-19', 1,1 ), 
('2013-04-18', 0,1 ), 
('2013-04-17', 0,1 ), 
('2013-04-17', 1,2 ), 
('2013-04-16', 1,1 ), 
('2013-04-16', 0 ,2); 

2 -

SELECT a.snapdate, a.value 
FROM ( 
  SELECT t1.*, COUNT(*) AS rank 
  FROM changes t1
  LEFT JOIN changes t2 ON t1.snapdate >= t2.snapdate 
  GROUP BY t1.snapdate 
) AS a 
LEFT JOIN ( 
  SELECT t1.*, COUNT(*) AS rank 
  FROM changes t1
  LEFT JOIN changes t2 ON t1.snapdate >= t2.snapdate 
  GROUP BY t1.snapdate 
) AS b ON a.rank = b.rank+1 AND a.value = b.value 
WHERE b.snapdate IS NULL
ORDER BY a.snapdate DESC;

工作得很好但是如何选择WHERE uid=2例如? 我不能使用临时表:

 create temporary table changes_temp
    as
    select *
    from changes
    where uid = 2 

http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html

2 个答案:

答案 0 :(得分:0)

添加where子句:

SELECT a.snapdate, a.value 
FROM ( 
  SELECT t1.*, COUNT(*) AS rank 
  FROM changes t1
  LEFT JOIN changes t2 ON t1.snapdate >= t2.snapdate 
  WHERE t1.uid = 2
  GROUP BY t1.snapdate 
) AS a 
LEFT JOIN ( 
  SELECT t1.*, COUNT(*) AS rank 
  FROM changes t1
  LEFT JOIN changes t2 ON t1.snapdate >= t2.snapdate 
  WHERE t1.uid = 2
  GROUP BY t1.snapdate 
) AS b ON a.rank = b.rank+1 AND a.value = b.value 
WHERE b.snapdate IS NULL
ORDER BY a.snapdate DESC;

sqlfiddle

答案 1 :(得分:0)

尝试在子查询中添加WHERE子句

    SELECT a.snapdate, a.value 
FROM ( 
  SELECT t1.*, COUNT(*) AS rank 
  FROM changes t1
  LEFT JOIN changes t2 ON t1.snapdate >= t2.snapdate 
  WHERE t2.uid=t1.uid AND t2.uid=2
  GROUP BY t1.snapdate 
) AS a 
LEFT JOIN ( 
  SELECT t1.*, COUNT(*) AS rank 
  FROM changes t1
  LEFT JOIN changes t2 ON t1.snapdate >= t2.snapdate 
  WHERE t2.uid=t1.uid AND t2.uid=2
  GROUP BY t1.snapdate 
) AS b ON a.rank = b.rank+1 AND a.value = b.value 
WHERE b.snapdate IS NULL
ORDER BY a.snapdate DESC;

创建SQLFiddle进行测试。 那是你要的吗 ?您没有解释查询的目标