› MySQL 5.5 Community Server
› MySQL 5.6 Community Server
› Percona Configuration Wizard
› XtraBackup 搭建主从复制
Great Sites on MySQL
› Percona
› MySQL Performance Blog
› Severalnines
推荐管理工具
› Sequel Pro
› phpMyAdmin
推荐书目
› MySQL Cookbook
MySQL 相关项目
› MariaDB
› Drizzle
参考文档
› http://mysql-python.sourceforge.net/MySQLdb.html
860670496
V2EX  ›  MySQL

自定义 ORDER BY 的问题

  •  
  •   860670496 · Aug 11, 2017 · 4601 views
    This topic created in 3352 days ago, the information mentioned may be changed or developed.
    新手,最近爬了个历史年表,公元纪年的字段是 varchar (例如公元前 32 年:“前 32 ”,公元 6 年:“ 6 ”,公元 1984:“ 1984 ”)。
    ORDER BY FIELD 貌似要把整个列表都写出来,显然不能行
    想问一下这种情况要怎么写才能按公元纪年的顺序排列呢?
    8 replies  •  2017-08-11 21:17:30 +08:00
    ayumilove
        1
    ayumilove  
       Aug 11, 2017
    把公元前 替换成 负数
    Alexisused
        2
    Alexisused  
       Aug 11, 2017
    1 楼说的对
    860670496
        3
    860670496  
    OP
       Aug 11, 2017
    @ayumilove #1 这个办法也想过,然后用+0 之类的办法就可以
    我更想知道的是 MySQL 支不支持 ORDER BY 一定的通用规则,直接能做到这种排列呢?
    xshwy
        4
    xshwy  
       Aug 11, 2017 via iPhone
    SELECT * FROM `SCHEDULE`
    WHERE RATE IS NOT NULL AND RATE!=''
    ORDER BY SCHEDULE_DATE , FIELD(START_TIME,'8:00','18:30','21:00','21:30')
    LeeSeoung
        5
    LeeSeoung  
       Aug 11, 2017
    order by 转化(字段) 转化就是你把 varchar 的公元信息转成数字一类的。。
    860670496
        6
    860670496  
    OP
       Aug 11, 2017
    @xshwy #4 field 的写法我查过,如果没写进去的字符串,会自动当作 0 来排序……

    使用函数 FIELD(str,str1,str2,str3,...)
    MySQL 的自定义排序,str 与 str1、str2、str3...进行比较,并按照 str1,str2,str3...的顺序输出,如果遇到 str 为 null 或者不存在 str1,str2,str3...中的情况的则序列为 0

    我总不能把公元前的所有字符串都写一遍吧?

    @LeeSeoung #5 这个我以前就用过,问题是 CAST 或者 CONVERT 没办法处理“前 32 ”这种情况啊

    本来还思考过加一个 ID 字段来排序,后来一想这个表以后说不定还要在中间年份插入记录,肯定不会只往后加……现在暂时就采取 1 楼的办法 update 一下吧,多谢各位
    LeeSeoung
        7
    LeeSeoung  
       Aug 11, 2017
    平时用的 oracle 有 regexp_replace 这样的函数,查了下 mysql 并没有,可以利用下面的语句实现类似的功能吧

    IF(url REGEXP 'test.yahoo.com.cn',REPLACE(url,'www1.sohu.com','www.sina.com'),REPLACE(url,'www2.yahoo.com','www.sina.com'))
    finull
        8
    finull  
       Aug 11, 2017
    ORDER BY ( CASE WHEN date LIKE '前%' THEN 0 - SUBSTRING(date, 2) ELSE date END )

    可能有类型转化问题,试试
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1054 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 18:19 · PVG 02:19 · LAX 11:19 · JFK 14:19
    ♥ Do have faith in what you're doing.