繁体   English   中英

SQL:如何在一个查询中同时使用 GROUP BY 和 ORDER BY

[英]SQL: How to use GROUP BY and ORDER BY together in one query

我正在从我的数据库中获取座位预订,并想获取最新条目并将其与 Patient_reg_no 分组这是我的代码,

SELECT * 
FROM seat_booking 
WHERE patient_reg_no like '" . $_POST["keyword"] . "%' and is_active = 'Y' 
GROUP BY patient_reg_no 
ORDER BY booking_id DESC LIMIT 20

请试试这个

select patient_reg_no ,booking_id 
from
(SELECT patient_reg_no , booking_id 
,rank() over (partiotion by patient_reg_no  order by booking_id  desc) rank
FROM seat_booking 
WHERE patient_reg_no like '" . $_POST["keyword"] . "%' and is_active = 'Y' 
)a
where rank=1

问题是您选择在 select 列中使用通配符:*。 数据库不知道要按哪些列进行分组,因为您选择了所有列。 我添加了一个表别名来分配列名的域。 如果您决定加入另一个表,这将有很大帮助。

SELECT sb.patient_reg_no, sb.booking_id
FROM seat_booking sb
WHERE sb.patient_reg_no like '" . $_POST["keyword"] . "%' and sb.is_active = 'Y' 
GROUP BY sb.patient_reg_no
ORDER BY sb.booking_id DESC;
-- LIMIT 20;  -- Remove the limit until the results are correct

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM