1

我有一个脚本,它运行 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”。

4

4 回答 4

2

order by您可以单独执行此操作:

SELECT *
FROM records
WHERE [other where conditions]
ORDER BY (case when features >= $timestamp then featured else $timestamp end) DESC,
         created desc;
于 2013-09-05T19:53:52.783 回答
1

你可以用IF()这个。

SELECT * FROM records
WHERE [other where conditions]
ORDER BY IF(featured >= $timestamp, featured, created) DESC
于 2013-09-05T19:52:56.413 回答
1

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

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;
于 2013-09-05T19:53:53.103 回答
0

您可以在返回的行中创建一个特色标志,如下所示:

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

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

于 2013-09-05T19:53:48.080 回答