2013-06-13 58 views
0

1 -MYSQL:選擇更改的行,其中

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

回答

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進行測試。 這就是你想要的嗎?你沒有解釋你的查詢的目標

+0

只是一個單詞==> PERFECT – OlZ

+0

http://stackoverflow.com/questions/17085069/mysql-select-changed-row – OlZ

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