Это мой запрос:

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

что я хочу:

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
0
Amit Joshi 22 Фев 2016 в 10:13

2 ответа

Лучший ответ

Попробуй это

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
0
Vipin Jain 22 Фев 2016 в 07:19

Похоже, вам нужна только последняя запись на 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, поскольку вы выбираете из той же таблицы.

0
Giorgos Betsos 22 Фев 2016 в 07:27