mysql内部联接第二个表排序最近

omhiaaxx  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(259)

我有两张table categories 以及 equipment .
选择时,我希望按类别分组并显示该类别中最新的设备,但是我的查询将只返回该类别中的第一个设备。
我的问题如下:

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 JOIN 以及 date_added ASC 但这并没有改变什么。

qyswt5oh

qyswt5oh1#

您可以使用子查询的联接来表示max date

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

相关问题