本節簡單介紹了在PostgreSQL中容易出錯但又容易被忽略的細節。
除法運算
在整數和整數之間執行除法運算時,結果會是整數,但實際上我們希望保留小數位。
[local:/data/pg12]:5432 pg12@testdb=# select 1/2;
?column?
----------
0
(1 row)
[local:/data/pg12]:5432 pg12@testdb=#
查詢操作符”/“的定義
[local:/data/pg12]:5432 pg12@testdb=# select oprname,oprleft::regtype,oprright::regtype,oprresult::regtype from pg_operator where oprname = '/';
oprname | oprleft | oprright | oprresult
---------+------------------+------------------+------------------
/ | smallint | smallint | smallint
/ | integer | integer | integer
/ | smallint | integer | integer
/ | integer | smallint | integer
/ | real | real | real
/ | double precision | double precision | double precision
/ | bigint | bigint | bigint
/ | bigint | integer | bigint
/ | integer | bigint | bigint
/ | bigint | smallint | bigint
/ | smallint | bigint | bigint
/ | point | point | point
/ | path | point | path
/ | box | point | box
/ | money | real | money
/ | money | double precision | money
/ | money | bigint | money
/ | money | integer | money
/ | money | smallint | money
/ | money | money | double precision
/ | real | double precision | double precision
/ | double precision | real | double precision
/ | circle | point | circle
/ | interval | double precision | interval
/ | numeric | numeric | numeric
(25 rows)
[local:/data/pg12]:5432 pg12@testdb=#
在PG中,整型之間的除法得到的結果為整型,如結果需要得到浮點數或實數,則需要執行類型轉換,比如把其中一個算子轉換為float或者numeric
[local:/data/pg12]:5432 pg12@testdb=# select 1/2::float;
?column?
----------
0.5
(1 row)
[local:/data/pg12]:5432 pg12@testdb=# select 1/2::numeric;
?column?
------------------------
0.50000000000000000000
(1 row)
[local:/data/pg12]:5432 pg12@testdb=#
被0除錯誤
如除數為0時,會報“ERROR: division by zero”錯誤,為免出現這種錯誤,可使用nullif判斷除數是否為0,如為0則返回null
[local:/data/pg12]:5432 pg12@testdb=# select 1/0;
ERROR: division by zero
[local:/data/pg12]:5432 pg12@testdb=# select 1/nullif(0,0);
?column?
----------
(1 row)
[local:/data/pg12]:5432 pg12@testdb=# select 1/nullif(0,0) is null;
?column?
----------
t
(1 row)
[local:/data/pg12]:5432 pg12@testdb=#
統計NULL值問題
如使用count(column)時,column的值如為null則不會統計到結果中,使用count(*)則會統計。
[local:/data/pg12]:5432 pg12@testdb=# create table t_count(id int);
CREATE TABLE
[local:/data/pg12]:5432 pg12@testdb=# insert into t_count select generate_series(1,1000);
INSERT 0 1000
[local:/data/pg12]:5432 pg12@testdb=# insert into t_count select null from generate_series(1,1000);
INSERT 0 1000
[local:/data/pg12]:5432 pg12@testdb=# select count(*) from t_count;
count
-------
2000
(1 row)
[local:/data/pg12]:5432 pg12@testdb=# select count(id) from t_count;
count
-------
1000
(1 row)
[local:/data/pg12]:5432 pg12@testdb=#
參考資料
https://hakibenita.com/sql-dos-and-donts
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。