简体   繁体   English

从mysql中的嵌套查询中获取结果后,按desc顺序

[英]Order in desc after getting result from a nested query in mysql

I have 2 tables. 我有2张桌子。 I get result in order by desc format. 我按desc格式按顺序得到结果。 Now I want to display info in that same order format. 现在,我要以相同的订单格式显示信息。 But I am not able to do that. 但我无法做到这一点。

select *
  from table1  
 where field in (select * 
                   from table2 
                  where StartDate > '2011-11-01' 
                    AND StartDate < '2011-11-30'
               group by field1 
               order by count(field1) desc );

The inner query is ordered in descending, but when used with the outer query, the order is lost. 内部查询按降序排列,但与外部查询一起使用时,该顺序丢失。

An in clause does not preserve ordering, I'm surprised MySQL even allows it like that :) 一个in子句不保留顺序,我很惊讶MySQL甚至允许它:)

One solution is to calculate the count in a subquery, and use that to order: 一种解决方案是在子查询中计算计数,然后使用该计数进行排序:

select  *
from    table1 t1
join    (
        select  field1
        ,       count(field1) as Field1Count
        from    table2 
        where   StartDate > '2011-11-01' 
                and StartDate < '2011-11-30'
        group by field1 
        ) t2
on      t1.field1 = t2.field1
order by
        t2.Field1Count desc

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

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