php - MYSQL order by - 遵循一种模式

标签 php python mysql sql sql-order-by

我们如何为要选择或保存在变量中的结果设置模式。

所以基本上当我选择数据时,它的顺序如下。

customer ID               Email
1                         test@gmail.com
2                         test@hotmail.com
3                         test@yahoo.com
4                         test@seznam.cz

所以我要全选表中的记录!但是我想订购它们,以便它们遵循这种格式

customer ID               Email
1                         test@gmail.com
2                         test@hotmail.com
3                         test@yahoo.com
4                         test@seznam.cz
52                        test2@gmail.com
7                         test2@hotmail.com
84                        test2@yahoo.com
99                        test2@seznam.cz
10                        test3@gmail.com
11                        test3@hotmail.com
124                       test3@yahoo.com
1321                      test3@seznam.cz

那么我如何设置我的查询以使我的结果遵循类似的顺序。我基本上想知道如何从我的数据库中选择(或在存储后处理)数据以遵循特定模式。

编辑:

这是我正在尝试的脚本,它确实可以部分工作,但数据不符合模式。

SELECT DISTINCT customer_id, email
FROM customer_1_tbl
WHERE customer_id IN (
    SELECT cust.customer_id 
    FROM customer_1_binding_tbl AS cust 
    WHERE cust.mailinglist_id = '2') order by substring_index(email, '@', 1),
     (case substring_index(email, '@', -1)
          when ('gmail.com' or 'hotmail.com' or 'jednotavimperk.cz') then 1
          when ('seznam.cz' or 'email.cz' or 'post.cz') then 2
          when 'tiscali.cz' then 3
          when ('centrum.cz' or 'atlas.cz' or 'volny.cz') then 4
          else 999
      end)

最佳答案

您可以将 email 列分开。然后,使用 case 分配排序优先级:

order by substring_index(email, '@', 1),
         (case substring_index(email, '@', -1)
              when 'gmail.com' then 1
              when 'hotmail.com' then 2
              when 'yahoo.com' then 3
              when 'seznam.cz' then 4
              else 999
          end)

另一个方便的函数是 field()。但是,对于不匹配项,它并没有为您提供简单的 else 子句选项。

编辑:

您编辑的代码是错误的。这不是您在 case 中表达多个条件的方式。试试这个:

order by substring_index(email, '@', 1),
         (case when substring_index(email, '@', -1) in ('gmail.com', 'hotmail.com', 'jednotavimperk.cz') then 1
               when substring_index(email, '@', -1) in ('seznam.cz', 'email.cz', 'post.cz') then 2
               when substring_index(email, '@', -1) = 'tiscali.cz' then 3
               when substring_index(email, '@', -1) in ('centrum.cz', 'atlas.cz', 'volny.cz') then 4
               else 999
          end)

关于php - MYSQL order by - 遵循一种模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33102812/

相关文章:

php mysql 我需要一次读取一条记录直到结束

PHP 安全扫描器

javascript - 在Codeigniter中: How to give the image path in external js file

python - 在 Pygame、Python 3 中设置固定 FPS

PHP 5.4 无法在 Windows 7 上加载 mysql 或 pgsql 数据库

mysql - 将新行插入到连接到数据库上另一个表的表中

php - 在 PHP 中获取带有查询字符串的当前 URL 路径

php - mysqli 使用带有准备好的语句和查询的 select *

python - 如何使用 matplotlib 从 csv 绘制特定日期和时间的数据?

python - 如何使用pyplot在曲面图后面画一条线