我的数据库中有一个表,我希望按特定顺序提取数据 以下是该表的示例:
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;
我表中的有效条目是:
我想提取数据的顺序是:
到目前为止,我使用了三个与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;
我自己觉得这需要很多必要的代码来完成它并希望有更好的解决方案。
那么还有更好的方法吗?
答案 0 :(得分:1)
只需将您的条件放入一个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将布尔值视为数字上下文中的数字,“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)