mysql|unsigned 與 signed 類型


通過mysql的數值類型設置,控制數值的正負

1,如何使用

在mysql的編輯器中,可以直接定義 bigint(20) unsigned

 

 

 2, 發揮的作用

一般默認定義的數據類型為signed(有符號類型),取值返回包含有負數范圍,一般正負值的差依然等於無符號類型的范圍的上限值。

當定義為unsigned(無符號類型)時, 取值范圍僅為正數范圍,下限值為0;

3,當設置為unsigned時候,報錯BIGINT UNSIGNED value is out of range....如何解決

使用unsigned限制數值范圍為正數的時候,如果執行相減操作產生負數;就會報錯;解決方法

-- 需要添加四個計算值計算每日變化數據
-- dayConfirmed: 每日確診
-- dayRecovered: 每日康復
-- dayDeaths: 每日死亡
-- dayExisting: 當日現存
select n.id,
       n.region_id,
       n.region_parent_id,
       n.recovered,
       n.deaths,
       n.day_date,
       n.confirmed,
       (cast(n.confirmed as signed) - cast(m.confirmed as signed)) as dayConfirmed,
       (cast(n.recovered as signed) - cast(m.recovered as signed)) as dayRecovered,
       (cast(n.deaths as signed) - cast(m.deaths as signed))       as dayDeaths,
       (cast(n.confirmed  as signed) - cast(n.recovered  as signed) - cast(n.deaths  as signed))    as dayExisting
from region_data_total as n
         join region_data_total as m on date_sub(n.day_date, interval 1 day) = m.day_date
where n.region_id = m.region_id and n.day_date = (select max(day_date) from region_data_total);

核心: 使用 cast(targetCol as signed) 將所有涉及到的unsigned字段先轉化為signed類型后,再進行運算

相關內容補充:

MYSQL的數據類型(菜鳥教程):

  • https://www.runoob.com/mysql/mysql-data-types.html 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM