如何在 MySQL 中模拟一个数组变量?
不要模拟数组变量,而是在 MySQL 中使用临时表。语法如下 -
create temporary table if not exists yourTemporaryTableName select yourColumnName1,yourColumnName2,......N from yourTableName where condition
为了理解上述语法,让我们首先创建一个表。创建表的查询如下 -
mysql> create table SimulateArrayDemo -> ( -> Id int, -> FirstName varchar(100), -> LastName varchar(100 -> ) -> ); Query OK, 0 rows affected (1.25 sec)
使用 insert 命令在表中插入一些记录。查询如下 -
mysql> insert into SimulateArrayDemo values(1,'Sam','Taylor'); Query OK, 1 row affected (0.10 sec) mysql> insert into SimulateArrayDemo values(2,'Carol','Taylor'); Query OK, 1 row affected (0.18 sec) mysql> insert into SimulateArrayDemo values(3,'Bob','Smith'); Query OK, 1 row affected (0.09 sec) mysql> insert into SimulateArrayDemo values(4,'David','Taylor'); Query OK, 1 row affected (0.16 sec) mysql> insert into SimulateArrayDemo values(5,'John','Smith'); Query OK, 1 row affected (0.11 sec) mysql> insert into SimulateArrayDemo values(6,'Mike','Taylor'); Query OK, 1 row affected (0.21 sec)
使用 select 语句从表中显示所有记录。查询如下 -
mysql> select *from SimulateArrayDemo;
输出
+------+-----------+----------+ | Id | FirstName | LastName | +------+-----------+----------+ | 1 | Sam | Taylor | | 2 | Carol | Taylor | | 3 | Bob | Smith | | 4 | David | Taylor | | 5 | John | Smith | | 6 | Mike | Taylor | +------+-----------+----------+ 6 rows in set (0.00 sec)
以下查询使用临时表模拟数组变量 -
mysql> create temporary table if not exists SimulationOfArray -> select Id,FirstName from SimulateArrayDemo where LastName='Taylor'; Query OK, 4 rows affected (0.10 sec) Records: 4 Duplicates: 0 Warnings: 0
从临时表中显示记录。查询如下 -
mysql> select *from SimulationOfArray;
输出
+------+-----------+ | Id | FirstName | +------+-----------+ | 1 | Sam | | 2 | Carol | | 4 | David | | 6 | Mike | +------+-----------+ 4 rows in set (0.00 sec)
广告