根据最新的created_at时间选择唯一行

时间:2016-02-22 07:13:13

标签: mysql sql

这是我的疑问:

var encrypted = encryptionDal.EncryptDataWithSalt(encryptionItems, salt);
var sb = new StringBuilder();
foreach (var kvp in encrypted)
    sb.AppendFormat("&{0}={1}", WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value));
var queryString = sb.ToString(1, sb.Length-1); // assuming non-empty

我得到了什么:

SELECT br.employee_id AS rat_id,
       br.rating_comment,
       br.created_at,
       br.id
FROM employee_followers
LEFT JOIN employee_ratings AS br ON employee_followers. employee_id = br.employee_id
WHERE employee_followers.employee_id IN
    (SELECT `employee_id`
     FROM employee_followers
     WHERE user_id =32)
GROUP BY br.id
ORDER BY created_at DESC

我想要的是什么:

rat_id    rating_comment        created_at              id
18        superb developer      2016-02-19 18:26:54     82
9         james to manoj-joshi  2016-02-19 16:42:17     84
50        james to prem         2016-02-19 13:05:30     83
50        pinal to prem         2016-02-19 12:20:00     73
50        prem to premal-joshi  2016-02-19 11:40:52     78
18        prem to mukund        2016-02-19 11:21:52     77
18        pinal to mukund       2016-02-18 11:37:00     76
9         mukund rate to mitesh 2016-02-15 22:34:14     51
9         Not a bad.            2016-02-10 00:16:31     45
9         sda                   2016-02-08 01:36:33     39

2 个答案:

答案 0 :(得分:0)

试试这个

SELECT rat_id,rating_comment, MAX(created_at) AS created, id FROM (
SELECT br.employee_id AS rat_id,
       br.rating_comment,
       br.created_at,
       br.id
FROM employee_followers
LEFT JOIN employee_ratings AS br ON employee_followers. employee_id = br.employee_id
WHERE employee_followers.employee_id IN
    (SELECT `employee_id`
     FROM employee_followers
     WHERE user_id =32)
GROUP BY br.id
ORDER BY created_at DESC) AS temp GROUP BY temp.rat_id

答案 1 :(得分:0)

您似乎只想要每employee_id的最新记录。您可以使用派生表获取最大日期,然后再次加入以获取此日期employee_ratings表中的所有字段:

SELECT er.employee_id AS rat_id,
       er.rating_comment,
       er.created_at,
       er.id
FROM employee_followers AS ef
LEFT JOIN (
   SELECT employee_id, MAX(created_at) AS max_date
   FROM employee_ratings
   GROUP BY employee_id
) AS emp_max ON ef.employee_id = emp_max.employee_id 
LEFT JOIN employee_ratings AS er 
   ON emp_max.employee_id = er.employee_id AND
      emp_max.max_date = er.max_date
WHERE user_id = 32
ORDER BY created_at DESC

我还删除了GROUP BY br.id,它在查询的上下文中似乎是多余的。此IN运算符也可以由user_id = 32替换,因为您从同一个表中进行选择。