![](/img/trans.png)
[英]sql query that involves OR won't return results if one of the tables empty
[英]SQL Query, Subquery won't return data
問題:我的查詢返回NULL潛在問題:子查詢格式錯誤,並且僅當我要排序的某些數據在數據集中時才有效。
今天的代碼示例:
SELECT production_order
,SUM(total_working_time_h) - (SELECT SUM(total_working_time_h) FROM {$table} WHERE production_order = '$production_order' AND (station = '出貨檢驗 | OQC' OR production_type = 'Rework')) AS total_working_time_h_edit
,SUM(no_of_defects) AS no_of_defects_during_production
FROM {$table}
WHERE production_order = '$production_order'
只要我在此生產訂單的數據庫中登錄了“返工”和/或“'檢驗檢驗| OQC'”,此方法就很好用。 如果沒有,除了NULL之外我什么也不會得到。 所以我的問題在我的子查詢中的某個地方:
SELECT SUM(total_working_time_h) FROM {$table} WHERE production_order = '$production_order' AND (station = '出貨檢驗 | OQC' OR production_type = 'Rework')
我嘗試添加“ 0”以確保它獲得0而不是NULL,但沒有成功,如下所示:
(0 + SELECT SUM(total_working_time_h) FROM {$table} WHERE production_order = '$production_order' AND (station = '出貨檢驗 | OQC' OR production_type = 'Rework')
格式化為文本的示例數據集:
production_order part_nr station total_working_time_h
26135 129-108816B-UL 壓接 | Crimping 1.42
26135 129-108816B 線束組裝 | Harness Assembling 7.67
26135 129-108816 測試 | Testing 0.83
26135 129-108816B 外觀全檢 | Appearance inspection 0.83
給出以下輸出:
production_order,total_working_time_h_edit
26135, NULL
我想要這個輸出:
production_order,total_working_time_h_edit
26135, 10,45
如果我的數據集包含要排序的樁號或要對其進行排序的production_type,則一切正常。 但是,如果這兩個數據集中都缺失,則返回NULL,因為我認為這是因為子查詢返回0。
我正在使用的不同數據集的示例。 如果我在數據集中用綠色單元格標記的數據將起作用。 如果沒有,我得到如上所述的返回NULL。
那么如何使我的子查詢不返回NULL?
設法自己解決了這個問題。
問題:子查詢返回NULL而不是0。
解決方案:將COALESCE(,0)添加到我的子查詢函數SUM()中,如下所示:
COALESCE(SUM(total_working_time_h),0)
這樣,當SUM()實際上想要返回NULL時,它將返回0而不是NULL。 那解決了我的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.