【问题标题】:MySQL order by value1 unless value1 < 0, then order by value2MySQL 按 value1 排序,除非 value1 < 0,然后按 value2 排序
【发布时间】:2013-09-06 18:49:04
【问题描述】:

我有一个脚本,它运行 2 个几乎相同的相当慢的 SQL 查询。从数据库记录中选择应该在页面上“突出显示”的记录,即它们排在第一位。另一个从数据库中选择常规记录。每个查询大约需要 0.3 秒,由于两者同时运行,我在它们上损失了 0.6 秒。所以我想知道是否可以组合这些查询。以下是它们的样子:

SELECT * FROM records WHERE [other where conditions] AND featured>=$timestamp ORDER BY featured DESC

SELECT * FROM records WHERE [other where conditions] AND featured<$timestamp ORDER BY created DESC

我标记的 [其他条件] 在这两种情况下都是相同的。所以我基本上需要做的是:

SELECT * FROM records WHERE [other where conditions] ORDER BY featured DESC UNLESS featured < $timestamp, created DESC

除了我不知道如何告诉 MySQL“ORDER BY ... UNLESS”。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您可以单独使用 order by 来做到这一点:

    SELECT *
    FROM records
    WHERE [other where conditions]
    ORDER BY (case when features >= $timestamp then featured else $timestamp end) DESC,
             created desc;
    

    【讨论】:

    • 谢谢,这非常适合我的情况,因为我有时需要对创建的 asc 进行排序。使用 if() 的顺序,我只能用两种排序方法朝着同一个方向前进。
    • 这个答案中的 AND 不是错误的吗?使用此查询,您只会得到以 >= $timestamp 开头的结果。
    • @para 。 . .接得好。删除它。
    【解决方案2】:

    您可以为此使用IF()

    SELECT * FROM records
    WHERE [other where conditions]
    ORDER BY IF(featured >= $timestamp, featured, created) DESC
    

    【讨论】:

    • 现在如果我需要按特色 DESC 排序并创建 ASC 怎么办? (有时会发生)
    【解决方案3】:

    是的,你可以这样做,代码是这样的:

    SELECT * FROM records 
        WHERE [other where conditions] 
    ORDER BY 
        IF(featured < $timestamp, created, featured) DESC
    

    而php版本会是这样的:

    $timestamp = now();
    $SQLCond = "id = 4";
    $SQLLimit = "LIMIT 0, 100";
    $SQLMask = "SELECT * FROM records where " . $SQLCond . " ORDER BY IF(featured < " . mysql_real_escape_string($timestamp) . ", created, featured) DESC " . $SQLLimit;
    

    【讨论】:

      【解决方案4】:

      您可以像这样在返回的行中创建一个特色标志:

      SELECT CASE WHEN featured>=$timestamp THEN 1 ELSE 0 END AS `featuredRecord`, *
      FROM records
      WHERE [other where conditions]
      ORDER BY featured DESC
      

      第一条记录应为特色记录,其余为常规记录。

      【讨论】:

      • 我猜你的意思是ORDER BY featuredRecord
      • 看起来特色字段是日期/时间,所以应该没问题。在这种情况下,特色记录似乎是由它们的新颖性定义的,应该首先出现。
      猜你喜欢
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多