簡體   English   中英

基於空值獲取排序的SQL查詢的最佳方法是什么

[英]What is the best way to get sorted SQL query based on null values

我的數據庫中有一張表格,我想按特定順序提取數據。
這是表格的示例:

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;

我表中的有效條目是:

  • 必須填寫field1
  • 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將您的條件放入一個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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM