SQL连接排序和限制结果

时间:2016-04-14 18:29:34

标签: sql postgresql join

我有以下两个表(填充了更多数据):

等级

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

我想从推荐表中每一行的评级表中选择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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

答案 2 :(得分: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