2014-02-14 55 views
2

我在數據庫中有一個表,我想通過某些條件從中選擇最近的行。選擇最新行

我做了一個fiddle以更好地解釋我的需求。你可以看到,我已經嘗試創建一個查詢來獲取我想要的數據。但不幸的是,我不僅得到最新的行,而且實際上每一行都符合條件,但符合日期。

我試圖解釋什麼,我想與僞SQL:

SELECT * FROM test WHERE date = Max(date) AND user = 'Timmy'; 

編輯:現在看來似乎並不完全清楚我想要什麼。 'date'描述配置文件的創建日期。所以我想獲得'蒂米'的最新資料。

回答

10

如果你想返回具有與之相關聯的最近日期的行,你也可以使用子查詢得到的結果:

select t1.description, 
    t1.date, 
    t1.profile, 
    t1.user, 
    Replace(t1.locations, ',', '|') locations 
from test t1 
inner join 
(
    select max(date) date, profile, user 
    from test 
    group by profile, user 
) t2 
    on t1.user = t2.user 
    and t1.date = t2.date 
    and t1.profile = t2.profile 
where t1.user = 'Timmy' 
order by t1.profile 

SQL Fiddle with Demo

子查詢將返回每個用戶和配置文件的最大日期,然後將它加回到用戶,配置文件和日期的表上,以返回每個用戶的每個配置文件的最近行(或者像這裏一樣,針對特定用戶的每個配置文件)。

+3

*'我想**每個**最新的'Timmy'個人資料* * - 我相信'profile'也應該包含在'GROUP BY' –

+0

@AndriyM是的,我想你是對的。更新了我的答案。謝謝 – Taryn

3
SELECT description, 
     date, 
     profile, 
     user, 
     Replace(locations, ',', '|') AS locations 
FROM test AS t 
WHERE date = (
        SELECT date 
        FROM test AS tm 
        WHERE tm.user = t.user 
        ORDER BY date DESC 
        LIMIT 1 
       ) 
    AND user = 'Timmy' 
ORDER BY profile ;  -- whatever 
+0

單擊此處查看[SQL小提琴](http://sqlfiddle.com/#!2/4ff08/67) –

+1

這只是解決問題的唯一答案。 –

+0

點擊此處查看[更新的SQL小提琴](http://sqlfiddle.com/#!2/4ff08/82) –