使用 MySQL 中的 CASE WHEN 獲得表是否存在布林結果


為此,可以使用 INFORMATION_SCHEMA.TABLES 查詢要搜尋的表。我們先建立一個表 −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.57 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable values(101,'Chris');
Query OK, 1 row affected (0.71 sec)
mysql> insert into DemoTable values(102,'David');
Query OK, 1 row affected (0.20 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

這將產生以下輸出 −

+------+-------+
|   Id | Name  |
+------+-------+
|  101 | Chris |
|  102 | David |
+------+-------+
2 rows in set (0.00 sec)

以下是對錶是否存在進行檢查的查詢 −

mysql> select max(case when table_name = 'DemoTable' then 'Yes the table
exist(TRUE)' else 'No(FALSE)' end) AS isTableExists
   -> from information_schema.tables;

這將產生以下輸出 −

+-------------------------------+
| isTableExists                 |
+-------------------------------+
| Yes the table exist(TRUE)     |
+-------------------------------+
1 row in set (0.52 sec)

更新於:2019-12-13

268 次瀏覽

開始你的 職業

完成課程獲取認證

開始
廣告
© . All rights reserved.