doubi7346 2013-11-14 12:12
浏览 25

在订购每个查询结果后联合多个mysql查询

I have two queries on the same table that need to be joined into one mysqli result. The issue that is proving to be quite unique is ordering the individual statements, and THEN merging into one result, preserving the order, so I can iterate through each result.

Here is the simplified version of the query:

"SELECT number FROM items WHERE number > 0 ORDER BY number ASC"

"SELECT number FROM items WHERE number >= 0 ORDER BY number  DESC"

So given a table with both positive and negative values, the result should be as such:

1, 2, 3, 4, 5, 0, -1, -2, -3, -4, -5

Then the results are put through a PHP while loop.

  • 写回答

1条回答 默认 最新

  • douliangli6407 2013-11-14 14:32
    关注

    Something like this should work:

    SELECT number FROM (
        SELECT * FROM (
            SELECT number, number AS sort1, 'a' AS sort2 FROM items WHERE number > 0 ORDER BY number ASC
        ) s1
        UNION
            SELECT 0, 'b', 0 FROM items WHERE number = 0
        UNION SELECT * FROM (
            SELECT number, 'c' AS sort1, number AS sort2 FROM items WHERE number < 0 ORDER BY number  DESC
        ) s2
    ) ss1
    ORDER BY ss1.sort1 ASC, ss1.sort2 ASC
    

    This select the 3 parts of the result with different sort tags, so that you can use them to order how you want. The trick part is putting the 0 where it is.

    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退