【问题标题】:Order in desc after getting result from a nested query in mysql从 mysql 中的嵌套查询获取结果后按 desc 排序
【发布时间】:2012-02-20 06:07:58
【问题描述】:

我有 2 张桌子。我按 desc 格式得到结果。 现在我想以相同的订单格式显示信息。但我做不到。

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 );

内部查询按降序排列,但与外部查询一起使用时,顺序会丢失。

【问题讨论】:

  • 该查询应该返回一个错误,将table1.fieldtable2 中的所有列进行比较...
  • 您确定这是您的实际工作查询吗? where field in (select * from 看起来很奇怪。
  • 是的。但我想出了答案。谢谢。

标签: mysql sql


【解决方案1】:

in 子句不保留顺序,我很惊讶 MySQL 竟然允许这样 :)

一种解决方案是计算子查询中的计数,并使用它来订购:

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

【讨论】:

    猜你喜欢
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2017-07-11
    • 2021-03-02
    • 1970-01-01
    相关资源
    最近更新 更多