如何在 MySQL 中通过拼接选择符合条件的行?
可以使用 CONCAT_WS() 实现此操作。让我们创建一个表 −
mysql> create table demo38 −> ( −> user_id int, −> user_first_name varchar(20), −> user_last_name varchar(20), −> user_date_of_birth date −> ); Query OK, 0 rows affected (1.70 sec)
使用 insert 命令向表中插入一些记录 −
mysql> insert into demo38 values(10,'John','Smith','1990−10−01'); Query OK, 1 row affected (0.14 sec) mysql> insert into demo38 values(11,'David','Miller','1994−01−21'); Query OK, 1 row affected (0.13 sec) mysql> insert into demo38 values(11,'John','Doe','1992−02−01'); Query OK, 1 row affected (0.13 sec) mysql> insert into demo38 values(12,'Adam','Smith','1996−11−11'); Query OK, 1 row affected (0.11 sec) mysql> insert into demo38 values(13,'Chris','Brown','1997−03−10'); Query OK, 1 row affected (0.13 sec)
使用 select 语句从表中显示记录 −
mysql> select *from demo38;
将生成以下输出 −
+---------+-----------------+----------------+--------------------+ | user_id | user_first_name | user_last_name | user_date_of_birth | +---------+-----------------+----------------+--------------------+ | 10 | John | Smith | 1990−10−01 | | 11 | David | Miller | 1994−01−21 | | 11 | John | Doe | 1992−02−01 | | 12 | Adam | Smith | 1996−11−11 | | 13 | Chris | Brown | 1997−03−10 | +---------+-----------------+----------------+--------------------+ 5 rows in set (0.00 sec)
以下是选择符合条件的行所需的查询 −
mysql> select concat_ws('/',user_first_name, user_last_name,'the date of birth year is=', date_format(user_date_of_birth,'%Y')) as Output −> from demo38 −> where user_id in(11,13);
将生成以下输出 −
+----------------------------------------------+ | Output | +----------------------------------------------+ | David/Miller/the date of birth year is=/1994 | | John/Doe/the date of birth year is=/1992 | | Chris/Brown/the date of birth year is=/1997 | +----------------------------------------------+ 3 rows in set (0.00 sec)
广告