MySQL 以及許多數(shù)據(jù)庫管理系統(tǒng)使用二進(jìn)制來存儲(chǔ)數(shù)字?jǐn)?shù)據(jù)。但是,在查詢中,您可能需要將這些數(shù)字以十進(jìn)制格式顯示。MySQL 提供了一些函數(shù)來實(shí)現(xiàn)這一點(diǎn)。
SELECT HEX(col) AS hex, CAST(col AS UNSIGNED) AS decimal FROM table;
在上面的查詢中,HEX() 函數(shù)將列作為十六進(jìn)制值返回,而 CAST() 函數(shù)將列強(qiáng)制轉(zhuǎn)換為無符號(hào)整數(shù)值,并將其作為十進(jìn)制值返回。
如果希望在結(jié)果集中顯示十進(jìn)制值,則可以使用以下查詢:
SELECT HEX(col) AS hex, CAST(col AS UNSIGNED) AS decimal, FORMAT(CAST(col AS UNSIGNED), 0) AS decimal_formatted FROM table;
上述查詢使用 FORMAT() 函數(shù)來將無符號(hào)整數(shù)強(qiáng)制轉(zhuǎn)換為帶有千位分隔符的字符串,以便更易于讀取。
您還可以使用以下查詢將整個(gè)表中的所有列以十進(jìn)制格式顯示:
SELECT HEX(col1) AS hex_col1, CAST(col1 AS UNSIGNED) AS decimal_col1, FORMAT(CAST(col1 AS UNSIGNED), 0) AS decimal_formatted_col1, HEX(col2) AS hex_col2, CAST(col2 AS UNSIGNED) AS decimal_col2, FORMAT(CAST(col2 AS UNSIGNED), 0) AS decimal_formatted_col2, ... FROM table;
通過使用上述技巧,您可以更輕松地在查詢結(jié)果中顯示以二進(jìn)制格式存儲(chǔ)的數(shù)字。