两个mysql在一个查询中选择 - 一个接一个

时间:2016-05-07 18:08:19

标签: php mysql where

我有一个像这样的mysql表:

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

现在我想按以下顺序获取ID:首先

WHERE rank >= 1 ORDER BY rank ASC

之后:

WHERE rank = -1

如何只在一个mysql_query()中获得此内容?

3 个答案:

答案 0 :(得分:1)

尝试类似:

SELECT *
FROM mytable
WHERE rank >= 1
ORDER BY rank
UNION
SELECT *
FROM mytable
WHERE rank = -1

或类似的东西:

SELECT *
FROM mytable
WHERE rank >= 1
ORDER BY CASE WHEN rank>=1 
              THEN 0 
              ELSE 1,rank

答案 1 :(得分:0)

建议回答:

SELECT id FROM myTable WHERE rank >= 1 ORDER BY rank ASC
UNION
SELECT id FROM myTable WHERE rank = -1

根据我的理解,您需要一列ID,从ids WHERE rank >= 1 ORDER BY rank ASC开始,以ids WHERE rank = -1结尾。

以前的sql查询使用UNION,它从单独的SELECT查询中连接两个结果表。只有当您从每个UNION查询中生成相同的生成列时,才能应用SELECT,因此,如果您以后想要增加所获得的列数,请务必记住这一点。

答案 2 :(得分:0)

您还可以使用ELT映射排名。

<强>样品

Console.WriteLine("   Client [" + IP + "]  are logged");