【问题标题】:MYSQL order by - to follow a patternMYSQL order by - 遵循模式
【发布时间】:2016-01-11 05:05:49
【问题描述】:

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

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

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)

【问题讨论】:

  • 定义排序的模式是什么?
  • 电子邮件域。例如首先 gmail、yahoo、seznam..然后重复直到所有电子邮件都像这样订购。 @GordonLinoff
  • 可以使用 MySQL REGEXP exp: HAVING email REGEXP '[a-z]' ORDER BY email DESC

标签: php python mysql sql sql-order-by


【解决方案1】:

您可以将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)

【讨论】:

  • 不,这不起作用。它留下了一个非常不寻常的订单,但它与模式无关。
  • @invincible.superman 。 . .设置一个 SQL Fiddle。这似乎完全符合您的要求。
  • 但我遇到的问题是它不遵守那个顺序。尤其是我拥有的电子邮件地址的规模......我已经编辑了我的评论以向您展示我正在使用的内容。 @gordonLinoff
  • 您的case 声明与我的完全不同。我建议你修复它。