MySQL 查询语句,用于在一个单独的列中显示字符串的第一个字母
要获取字符串中的第一个字母,可以使用 LEFT() 函数。此方法允许您返回字符串左侧的字符。
让我们首先看一个例子,并创建一个表:
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100) ); Query OK, 0 rows affected (1.03 sec)
使用 insert 命令在表中插入一些记录:
mysql> insert into DemoTable(FirstName) values('John'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(FirstName) values('Adam'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(FirstName) values('Jace'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(FirstName) values('Chris'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(FirstName) values('Bob'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(FirstName) values('Carol'); Query OK, 1 row affected (0.11 sec)
使用 select 语句显示表中的所有记录:
mysql> select *from DemoTable;
这将产生以下输出:
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Adam | | 3 | Jace | | 4 | Chris | | 5 | Bob | | 6 | Carol | +----+-----------+ 6 rows in set (0.00 sec)
以下是显示包含字符串值的列的第一个字母的查询。结果显示在新列中:
mysql> select Id,FirstName,upper(left(FirstName,1)) AS FirstLetter from DemoTable order by FirstName;
这将产生以下输出:
+----+-----------+-------------+ | Id | FirstName | FirstLetter | +----+-----------+-------------+ | 2 | Adam | A | | 5 | Bob | B | | 6 | Carol | C | | 4 | Chris | C | | 3 | Jace | J | | 1 | John | J | +----+-----------+-------------+ 6 rows in set (0.03 sec)
广告