Mysql 如何创建正确的查询?
我正在尝试编写一个查询: 从状态为3的用户中选择id 但是如果这个示例返回一个空响应,那么我需要改为选择id,其中status=4,如果它再次返回空响应,其中status=5Mysql 如何创建正确的查询?,mysql,sql,Mysql,Sql,我正在尝试编写一个查询: 从状态为3的用户中选择id 但是如果这个示例返回一个空响应,那么我需要改为选择id,其中status=4,如果它再次返回空响应,其中status=5 如何编写单个查询来解决此问题?您可以在运算符中使用或条件或使用 SELECT id FROM users WHERE status = 3 or status = 3 or status = 5 或 我想你只是想: SELECT id FROM users WHERE status >= 3 ORDER BY s
如何编写单个查询来解决此问题?您可以在运算符中使用或条件或使用
SELECT id FROM users WHERE status = 3 or status = 3 or status = 5
或
我想你只是想:
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));
我将在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
如果您有任何问题,请告诉我。假设您的桌子是这样的:
+----+--------+
| id | status |
+----+--------+
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 3 | 3 |
| 3 | 4 |
| 4 | 4 |
| 4 | 5 |
| 5 | 5 |
+----+--------+
+----+-------------+
| id | MIN(status) |
+----+-------------+
| 1 | 3 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
+----+-------------+
根据您希望首先看到每个id的最低状态的情况,可以使用MIN运算符。
因此,根据您最初的查询:
SELECT id,MIN(status) FROM users GROUP BY id;
然后你会得到这样的结果:
+----+--------+
| id | status |
+----+--------+
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 3 | 3 |
| 3 | 4 |
| 4 | 4 |
| 4 | 5 |
| 5 | 5 |
+----+--------+
+----+-------------+
| id | MIN(status) |
+----+-------------+
| 1 | 3 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
+----+-------------+
听起来您想在WHERE子句中使用子查询。此列id唯一吗?如果status=5的结果也是空的,那么您需要搜索status=6的结果吗?status 5永远不能为空,至少有一个status为5的用户是excistSounds wierd,但在10次中有9次您可以更好地重写它,以合并所有类型的查询,例如status=3的用户的SELECT id UNION。。。状态=4…联合。。。status=5 Oracle的数据库对大多数或IN查询自动重新布线。或者因为这些都是递增的值,所以最好使用介于3和5之间的状态,并强制进行范围扫描。可能是OP开始学习查询,我想为他提供一个选项,可能是我将立即删除答案。此查询将返回状态5,即使状态3存在。不幸的是,我需要获取所有具有此状态的用户,而不是仅一个