如何创建正确的查询?

时间:2019-04-24 19:05:35

标签: mysql sql

我正在尝试编写查询:

SELECT id FROM users WHERE status = 3

但是,如果此示例返回一个空响应,那么我需要在status = 4处选择id,如果它再次返回空,则在status = 5处。

如何编写单个查询来解决此问题?

4 个答案:

答案 0 :(得分:4)

我想你只是想要

SELECT id
FROM users 
WHERE status >= 3
ORDER BY status asc
LIMIT 1;

如果您想要多个用户:

SELECT u.id
FROM users u
WHERE u.status = (SELECT MIN(u2.status)
                  FROM users u2
                  WHERE u2.status >= 3
                 );

如果您有要测试的固定列表,也可以使用:

select u.id
from users u
where u.status = 3
union all
select u.id
from users u
where u.status = 4 and
      not exists (select 1 from users u2 where u2.status in (3))
union all
select u.id
from users u
where u.status = 5 and
      not exists (select 1 from users u2 where u2.status in (3, 4));

答案 1 :(得分:3)

您可以使用OR条件或使用IN运算符

SELECT id FROM users WHERE status = 3 or status = 3 or status = 5

SELECT id FROM users WHERE status IN (3,4,5)

答案 2 :(得分:0)

我将在where子句中使用case语句:

select id 
from users
where status = case when status = 3 and id is null then 4
                    when status = 4 and id is null then 5
               else 3
               end

如果您有任何问题,请告诉我。

答案 3 :(得分:0)

假设您的表格如下所示:

+----+--------+
| id | status |
+----+--------+
|  1 |      3 |
|  1 |      4 |
|  1 |      5 |
|  3 |      3 |
|  3 |      4 |
|  4 |      4 |
|  4 |      5 |
|  5 |      5 |
+----+--------+

根据您希望首先看到每个ID的最低状态的条件,可以使用MIN()运算符。 因此,根据您的原始查询:

SELECT id,MIN(status) FROM users GROUP BY id;

然后您将得到如下结果:

+----+-------------+
| id | MIN(status) |
+----+-------------+
|  1 |      3      |
|  3 |      3      |
|  4 |      4      |
|  5 |      5      |
+----+-------------+