MYSQL内部联接第二个表排序最新

时间:2018-08-03 07:33:13

标签: mysql join select mysqli inner-join

我有2个表categoriesequipment

选择时,我想按类别分组并显示该类别中的最新设备,但是我的查询将仅返回该类别中的第一台设备。

我的查询如下:

SELECT C.*, E.`photos` AS `photos`, E.`name` AS ename, E.`url` AS `eurl` FROM `categories` AS C INNER JOIN `equipment` E ON C.id=E.category WHERE C.`offon`=1 GROUP BY `category` ORDER BY C.`name` ASC, E.`date_added` DESC

我尝试使用JOIN而不是INNER JOINdate_added ASC,但这并没有改变。

预先感谢

1 个答案:

答案 0 :(得分:2)

您可以将子查询与联接用于最大日期

SELECT C.*
    , E.`photos` AS `photos`
    , E.`name` AS ename
    , E.`url` AS `eurl` 
FROM `categories` AS C 
INNER JOIN `equipment` E ON C.id=E.category  and  C.`offon`=1 
inner join  (
  select category , max(`date_added`) max_date
  from  `equipment` 
  group by category 

) t on t.max_date = E.date_added and C.id=E.category