我的数据库中有一个表,我想按特定顺序提取数据。
以下是该表的示例:
CREATE TABLE `test` (
`field1` int(11) NOT NULL,
`field2` int(11) DEFAULT NULL,
`field3` int(11) DEFAULT NULL,
UNIQUE KEY `field1_2` (`field1`,`field2`),
UNIQUE KEY `field1_3` (`field1`,`field3`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我的表格中的有效条目是:
- 必须填写字段1
- field2 可以为 null,也可以为基于 field1 和 field2 的唯一值
- field3 可以为 null,也可以为基于 field1 和 field3 的唯一值
我想要提取数据的顺序是:
- field2 和 field3 为 null 的所有字段
- field2 为 null 且 field3 为值的所有字段
- field3 为 null 且 field2 为值的所有字段
到目前为止,我已经使用了三个与 UNION 连接的查询
SELECT * FROM test WHERE field2 IS NULL
AND field3 IS NULL UNION
SELECT * FROM test WHERE field2 IS NULL
AND field3 IS NOT NULL UNION
SELECT * FROM test WHERE field2 IS NOT NULL
AND field3 IS NULL;
我自己觉得这是非常必要的代码来使其有序,并希望有更好的解决方案。
那么有没有更好的办法呢?
最佳答案
只需将您的条件放入一个order by
中即可:
order by (field2 is null and field3 is null) desc,
(field2 is null and field3 is not null) desc,
(field2 is null and field3 is not null) desc
您可能还想添加一个where
:
where field2 is null or field3 is null
这是可行的,因为 MySQL 将 bool 值视为数字上下文中的数字,“true”为 1,“false”为 0。这就是需要 desc
的原因。您可以在标准 SQL 中将相同的内容表达为:
order by (case when field2 is null and field3 is null then 1
when field2 is null and field3 is not null then 2
when field2 is not null and field3 is null then 3
else 4
end)
关于mysql - 基于空值排序 SQL 查询的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31589609/