如果条件在 MySQL 中为真,如何在值上设置特殊字符?
对于条件,使用 IF()。让我们先创建一个表 −
mysql> create table DemoTable637 (ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,ClientName varchar(100),ClientAge int ); Query OK, 0 rows affected (0.82 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable637(ClientName,ClientAge) values('Chris',23); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable637(ClientName,ClientAge) values('Robert',24); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable637(ClientName,ClientAge) values('David',57); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable637(ClientName,ClientAge) values('Carol',60); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable637;
这将产生以下输出 −
+----------+------------+-----------+ | ClientId | ClientName | ClientAge | +----------+------------+-----------+ | 1 | Chris | 23 | | 2 | Robert | 24 | | 3 | David | 57 | | 4 | Carol | 60 | +----------+------------+-----------+ 4 rows in set (0.00 sec)
以下是如果条件为真则设置特殊字符的查询 −
mysql> select if(ClientName IS NOT NULL AND ClientAge > 50,ClientName,'-------------') from DemoTable637;
这将产生以下输出 −
+--------------------------------------------------------------------------+ | if(ClientName IS NOT NULL AND ClientAge > 50,ClientName,'-------------') | +--------------------------------------------------------------------------+ | ------------- | | ------------- | | David | | Carol | +--------------------------------------------------------------------------+ 4 rows in set (0.00 sec)
广告