我有一个运行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”。
答案 0 :(得分:2)
您可以单独使用order by
执行此操作:
SELECT *
FROM records
WHERE [other where conditions]
ORDER BY (case when features >= $timestamp then featured else $timestamp end) DESC,
created desc;
答案 1 :(得分:1)
您可以使用IF()
。
SELECT * FROM records
WHERE [other where conditions]
ORDER BY IF(featured >= $timestamp, featured, created) DESC
答案 2 :(得分: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;
答案 3 :(得分:0)
你可以在返回的行中创建一个特色标志,如下所示:
SELECT CASE WHEN featured>=$timestamp THEN 1 ELSE 0 END AS `featuredRecord`, *
FROM records
WHERE [other where conditions]
ORDER BY featured DESC
第一条记录应该是特色记录,其余记录是常规记录。