如何按特定列名处理两个组并按Dec特定列名处理顺序

时间:2019-05-05 07:34:45

标签: sql

实际上,我希望按列名desc进行数据排序,但它也使用按另一列名进行分组... 例如:

SELECT * ,schemes.depart_id,schemes.scheme_id as s_id FROM `message_details`
left join schemes on schemes.scheme_id=message_details.scheme_id 
left join department on department.id=schemes.depart_id
WHERE message_details.reciver_id=13 or message_details.sender_id=13
GROUP by message_details.scheme_id
HAVING  order by message_details.msg_id desc

但第一行结果不正确,不是最高的msg_id

SELECT * ,schemes.depart_id,schemes.scheme_id as s_id 
FROM `message_details`
left join schemes on schemes.scheme_id=message_details.scheme_id 
left join department on department.id=schemes.depart_id
WHERE message_details.reciver_id=13 or message_details.sender_id=13
GROUP by message_details.scheme_id
HAVING  order by message_details.msg_id desc

我希望在结果中显示按msg_id最高的scheme_id分组

1 个答案:

答案 0 :(得分:0)

您似乎想要过滤而不是聚合

没有示例数据和所需结果,很难准确说明要实现的逻辑。我怀疑这是沿着这些思路:

select . . .   -- list the columns you want here
from message_details md left join
     schemes s
     on s.scheme_id = md.scheme_id left join
     department d
     on d.id = s.depart_id
where 13 in (md.receiver_id, md.sender_id) and
      md.scheme_id = (select max(md2.scheme_id)
                      from message_details md2
                      where 13 in (md2.receiver_id, md2.sender_id)
                     );