MySQL X类单行优先级

时间:2014-12-29 15:27:10

标签: mysql

我有一个如下的select语句,我想优先考虑X行的单行。例如,我希望查询按照指示进行选择,但首先将结果放入“type = X”。例如,我的基本查询是:

SELECT id,type,rank
FROM stores
WHERE zip = "11217"
ORDER BY rank DESC;

这将返回:

+----+------+------+
| id | type | rank |
+----+------+------+
|  1 |   1  |  10  |
+----+------+------+
|  2 |   5  |   9  |
+----+------+------+
|  3 |   4  |   8  |
+----+------+------+
|  4 |   3  |   7  |
+----+------+------+
|  5 |   3  |   6  |
+----+------+------+
|  6 |   1  |   5  |
+----+------+------+

但是,我想只返回前3个结果:

SELECT id,type,rank
FROM stores
WHERE zip = "11217"
ORDER BY rank DESC
LIMIT 3;

+----+------+------+
| id | type | rank |
+----+------+------+
|  1 |   1  |  10  |
+----+------+------+
|  2 |   5  |   9  |
+----+------+------+
|  3 |   4  |   8  |
+----+------+------+

现在我想要返回最佳行(按等级降序排序),其中type = 3,然后是其他行,通常按等级排序。这将导致:

+----+------+------+
| id | type | rank |
+----+------+------+
|  4 |   3  |   7  |
+----+------+------+
|  1 |   1  |   10 |
+----+------+------+
|  2 |   5  |   9  |
+----+------+------+

我知道我可以使用UNION执行此操作,但在我的实际查询中,计算等级非常昂贵(包括多个衰减和距离函数)。所以我试图看看是否有办法在单个查询中返回上述结果。

1 个答案:

答案 0 :(得分:1)

您只需要更改order by

SELECT id, type, rank
FROM stores
WHERE zip = '11217'
ORDER BY (type = 3) DESC,
         rank DESC
LIMIT 3;

MySQL将布尔值视为数值上下文中的整数,其中1为true,0为false。得到真实的"首先,在条件之后需要DESC

编辑:

如果你有多行id = 3并且你只想要一行,你可以尝试这样的事情:

SELECT s.id, s.type, s.rank
FROM stores s cross join
     (select min(s.id) as id3 from stores s where type = 3) s3
WHERE zip = '11217'
ORDER BY (s.id = sd.id3) DESC,
         rank DESC
LIMIT 3;

这是相同的想法,但您需要计算您正在使用的id