mysql中怎么将多个字段拼接到一起
:mysql将多字段拼接成一个字段,有个concat(),concat_ws()函数的使用
一个学生表,如下图:
+------+----------+------+---------+------------+
| no | name | sex | classno | birth |
+------+----------+------+---------+------------+
| 1 | zhangsan | F | 1001 | 1998-07-09 |
| 2 | lisi | F | 1001 | 1990-08-29 |
| 8 | jack | M | 1002 | 2001-9-25 |
| 18 | ross | M | 1003 | 2001-1-1 |
| 12 | rots | M | 1004 | 2001-1-1 |
| 15 | chaina | M | 1003 | 2001-1-1 |
| 11 | sad | F | 1009 | 2012-09-09 |
+------+----------+------+---------+------------+
案例:查询出student表中学生姓名,性别拼接起来命名为name_sex,中间并以空格区分
1、concat函数语法:concat(字段1,' 拼接时字段间需填充的条件',字段2)from table;
mysql> select concat(name,'_',sex)name_sex from t_student;
+--------------+
| name_sex |
+--------------+
| zhangsan F |
| lisi F |
| jack M |
| ross M |
| rots M |
| chaina M |
| sad F |
+--------------+
7 rows in set (0.00 sec)
2、用concat_ws()函数解决:
concat_ws()语法:concat(' 拼接时字段间需填充的条件',字段1,字段2,字段3)
mysql> select concat_ws('_',name,sex,no)name_sex from t_student;
+----------------+
| name_sex |
+----------------+
| zhangsan F 1 |
| lisi F 2 |
| jack M 8 |
| ross M 18 |
| rots M 12 |
| chaina M 15 |
| sad F 11 |
+----------------+
7 rows in set (0.00 sec)
concat_ws()和concat()函数的区别:
concat_ws():在拼接的时候,不管是2个还是2个以上的字段,拼接时每个字段都会加上拼接时需填充的条件
concat():在拼接的时候,每个字段拼接时,字段间拼接的填充条件需要依次加入