MySQL ASCII() 用法与实例

在 MySQL 中, ASCII() 函数接受一个字符串作为参数,它返回给定字符串最左侧字符的数字 ASCII 代码。

发布于

在 MySQL 中, ASCII() 函数接受一个字符串作为参数,它返回给定字符串最左侧字符的数字 ASCII 代码。

本文将说明 MySQL ASCII() 函数的用法并给出了几个实例。

语法

您可以使用以下语法:

ASCII(str)

其中 str 是要从最左侧字符的 ASCII 代码中获取的字符串。

示例 1 – 获取字母的 ASCII 码

要获取字母 A 的 ASCII 码值,请使用以下语句:

SELECT ASCII('A');

输出:

+------------+
| ASCII('A') |
+------------+
|         65 |
+------------+

所以我们可以看到字母 A 的 ASCII 码是 77

示例 2 – 获取字符串首字母的 ASCII 码

ASCII() 函数可以接受一个字符串做参数,但是它只返回第一个字母的 ASCII 码,如下:

SELECT ASCII('Hello');

输出:

+----------------+
| ASCII('Hello') |
+----------------+
|             72 |
+----------------+

在本示例中,我们传入了 Hello 作为参数, ASCII() 返回了首字母 H 的 ASCII 码。

示例 3 – 区分大小写

大写字母的 ASCII 代码与小写字母不同。例:

SELECT
  ASCII('A'),
  ASCII('a');

输出:

+------------+------------+
| ASCII('A') | ASCII('a') |
+------------+------------+
|         65 |         97 |
+------------+------------+

示例 3 – 所有字母的 ASCII 码

要显示所有大写字母的 ASCII 码,请使用以下语句:

SELECT
    ASCII('A') AS "A",
    ASCII('B') AS "B",
    ASCII('C') AS "C",
    ASCII('D') AS "D",
    ASCII('E') AS "E",
    ASCII('F') AS "F",
    ASCII('G') AS "G",
    ASCII('H') AS "H",
    ASCII('I') AS "I",
    ASCII('J') AS "J",
    ASCII('K') AS "K",
    ASCII('L') AS "L",
    ASCII('M') AS "M",
    ASCII('N') AS "N",
    ASCII('O') AS "O",
    ASCII('P') AS "P",
    ASCII('Q') AS "Q",
    ASCII('R') AS "R",
    ASCII('S') AS "S",
    ASCII('T') AS "T",
    ASCII('U') AS "U",
    ASCII('V') AS "V",
    ASCII('W') AS "W",
    ASCII('X') AS "X",
    ASCII('Y') AS "Y",
    ASCII('Z') AS "Z"\G

输出:

A: 65
B: 66
C: 67
D: 68
E: 69
F: 70
G: 71
H: 72
I: 73
J: 74
K: 75
L: 76
M: 77
N: 78
O: 79
P: 80
Q: 81
R: 82
S: 83
T: 84
U: 85
V: 86
W: 87
X: 88
Y: 89
Z: 90

要显示所有小写字母的 ASCII 码,请使用以下语句:

SELECT
    ASCII('a') AS "a",
    ASCII('b') AS "b",
    ASCII('c') AS "c",
    ASCII('d') AS "d",
    ASCII('e') AS "e",
    ASCII('f') AS "f",
    ASCII('g') AS "g",
    ASCII('h') AS "h",
    ASCII('i') AS "i",
    ASCII('j') AS "j",
    ASCII('k') AS "k",
    ASCII('l') AS "l",
    ASCII('m') AS "m",
    ASCII('n') AS "n",
    ASCII('o') AS "o",
    ASCII('p') AS "p",
    ASCII('q') AS "q",
    ASCII('r') AS "r",
    ASCII('s') AS "s",
    ASCII('t') AS "t",
    ASCII('u') AS "u",
    ASCII('v') AS "v",
    ASCII('w') AS "w",
    ASCII('x') AS "x",
    ASCII('y') AS "y",
    ASCII('z') AS "z"\G

输出:

a: 97
b: 98
c: 99
d: 100
e: 101
f: 102
g: 103
h: 104
i: 105
j: 106
k: 107
l: 108
m: 109
n: 110
o: 111
p: 112
q: 113
r: 114
s: 115
t: 116
u: 117
v: 118
w: 119
x: 120
y: 121
z: 122