2016-04-14 76 views
1

我有以下兩個表(填充更多的數據):SQL加入排序和限制結果

評級

ID | user_id | rating_value | date 
1 1   0.6   2016-04-02 
2 2   0.75   2016-04-05 
3 1   0.4   2016-04-08 
4 2   0.5   2016-04-12 

推薦

ID | user_id | recommendation_text | date 
1 1   'a'     2016-04-03 
2 2   'b'     2016-04-07 
3 1   'c'     2016-04-09 

我想從每個行i的評級表中選擇recommendation_text,user_id和最新評級值在推薦表中。

我無法只返回了最新的評價值(預期)

SELECT rec.user_id, rec.recommendation_text, rec.recommendation.date, rating.rating_value, rating.date 
FROM recommendation AS rec 
JOIN rating 
ON rec.user_id = rating.user_id; 

返回所有值加入到建議。最終的結果,我想產生是:

user_id | recommendation_text | recommendation_date | rating_value | rating_date 
1   'a'     2016-04-03   0.6   2016-04-02 
2   'b'     2016-04-07   0.75   2016-04-05 
1   'c'     2016-04-09   0.4   2016-04-08 
+0

我認爲這裏有一條信息缺失,我不知道如何選擇哪個評級來附加到哪個建議。在您的示例查詢中,您只能加入用戶ID,但如果這是您關心的唯一密鑰,那麼每個用戶不會有超過一個建議。 ID是從一個表到另一個表的外鍵? – Kateract

+0

你正在使用哪些DBMS? –

+0

使用PostgreSQL –

回答

1

你可以試試下面的查詢將在工作的PostgreSQL,MySQL和SQL數據庫

SELECT rec.user_id, rec.recommendation_text, rec.date, rating.rating_value, rating.date 
FROM recommendation AS rec 
JOIN rating ON rec.user_id = rating.user_id 
JOIN 
(SELECT rec.id as id1, max(rating.id) as id2 
FROM recommendation AS rec 
JOIN rating 
ON rec.user_id = rating.user_id AND rec.date >rating.date 
GROUP BY rec.id) t 
on t.id1= rec.id and t.id2=rating.id; 

Demo link here

更新基於評論:

僅供參考,該查詢只會如果ID在你的等級表是在同一順序的等級表的日期工作。如果你結束了一個更高的ID的記錄,但更早的日期,那麼它將返回上級ID,而不是以後的日子

SELECT rec.user_id, rec.recommendation_text, rec.date, rating.rating_value, rating.date 
    FROM recommendation AS rec 
    JOIN rating ON rec.user_id = rating.user_id 
    JOIN 
    (SELECT rec.id as id1, max(rating.date) as id2 
    FROM recommendation AS rec 
    JOIN rating 
    ON rec.user_id = rating.user_id AND rec.date >rating.date 
    GROUP BY rec.id) t 
    on t.id1= rec.id and t.id2=rating.date; 

updated Demo link

+0

這工作就像一個魅力,謝謝!我仍對下半部分的實際操作有些困惑,但我會自己調試。 –

+0

說明:上面的部分爲JOIN生成多個結果,bottom部分包含日期檢查,然後爲每個推薦查找相應的最後評級的id(使用由rec.id'設置的max(rating.id)組),然後使用它作爲JOIN找到確切的建議文本。 – DhruvJoshi

+0

@DerekA。僅供參考,只有當您的評級表中的ID與評級表中的日期順序相同時,該查詢纔會有效。如果您最終得到的ID較高但日期較早的記錄,則會返回較高的ID而不是較晚的日期。 – Kateract

0

你可以嘗試這樣的:

SELECT rec.user_id, rec.recommendation_text, rec.recommendation.date, rating.rating_value, rating.date 
FROM recommendation AS rec 
JOIN rating 
ON rec.user_id = rating.user_id 
where recommendation.date = 
(Select top 1 rec_order.date from recommendation AS rec_order where recorder.user_id=rating.user_id); 
0

另一種方法,無需再選擇:

select rec.user_id, rec.recommendation_text, rec.dates, rat.rating_value, rat.dates 
from recommendation as rec 
left join rating as rat on rat.user_id = rec.user_id and rat.dates < rec.dates 
left join rating as rat1 
on rat.user_id = rat1.user_id and rat.dates < rat1.dates and rat1.dates < rec.dates 
where rat1.id is null