我有2个表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
,但这并没有改变。
预先感谢
答案 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