MySQL 根据组中(不在表中)另一个字段的最大值对一个字段进行分组
考虑下表:
un_id avl_id avl_date avl_status
1738 6377398 2011-03-10 unavailable
1738 6377399 2011-03-11 unavailable
1738 6377400 2011-03-12 unavailable
1738 6719067 2011-03-12 unavailable
1738 6719351 2011-03-12 available
1738 6377401 2011-03-13 unavailable
1738 6377402 2011-03-14 unavailable
1738 6377403 2011-03-15 unavailable
1738 6377404 2011-03-16 available
1738 6719068 2011-03-16 unavailable
1738 6719352 2011-03-16 available
这是从以下查询中获得的:
SELECT
tbl_unit.un_id,
tbl_availability.avl_id,
tbl_availability.avl_date,
tbl_availability.avl_status
FROM
tbl_unit
INNER JOIN
tbl_availability ON
tbl_unit.un_id = tbl_availability.un_id
WHERE
tbl_availability.avl_active='True' AND
tbl_unit.un_active='True' AND
tbl_availability.avl_date >= '2011-03-10' AND
tbl_availability.avl_date
我想要的是 GROUP BY un_id,以便仅显示具有最高 avl_id 的 avl_status。即:
un_id avl_id avl_date avl_status
1738 6377398 2011-03-10 unavailable
1738 6377399 2011-03-11 unavailable
1738 6719351 2011-03-12 available
1738 6377401 2011-03-13 booked
1738 6377402 2011-03-14 booked
1738 6377403 2011-03-15 booked
1738 6719352 2011-03-16 available
我尝试添加 GROUP BY 和 HAVING 子句以及各种子查询,但每次都失败......
感谢所有帮助! :) - 亚当。
Consider the following table:
un_id avl_id avl_date avl_status
1738 6377398 2011-03-10 unavailable
1738 6377399 2011-03-11 unavailable
1738 6377400 2011-03-12 unavailable
1738 6719067 2011-03-12 unavailable
1738 6719351 2011-03-12 available
1738 6377401 2011-03-13 unavailable
1738 6377402 2011-03-14 unavailable
1738 6377403 2011-03-15 unavailable
1738 6377404 2011-03-16 available
1738 6719068 2011-03-16 unavailable
1738 6719352 2011-03-16 available
Which is obtained from the following query:
SELECT
tbl_unit.un_id,
tbl_availability.avl_id,
tbl_availability.avl_date,
tbl_availability.avl_status
FROM
tbl_unit
INNER JOIN
tbl_availability ON
tbl_unit.un_id = tbl_availability.un_id
WHERE
tbl_availability.avl_active='True' AND
tbl_unit.un_active='True' AND
tbl_availability.avl_date >= '2011-03-10' AND
tbl_availability.avl_date
What I want is to GROUP BY un_id so that only the avl_status having the highest avl_id is displayed. i.e:
un_id avl_id avl_date avl_status 1738 6377398 2011-03-10 unavailable 1738 6377399 2011-03-11 unavailable 1738 6719351 2011-03-12 available 1738 6377401 2011-03-13 booked 1738 6377402 2011-03-14 booked 1738 6377403 2011-03-15 booked 1738 6719352 2011-03-16 available
I have tried adding GROUP BY and HAVING clauses and various subqueries, but I have failed every time....
All help appreciated! :)
- Adam.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
Try this: