与其模拟一个数组变量,不如使用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 -> ) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into SimulateArrayDemo values(1,'Sam','Taylor'); mysql> insert into SimulateArrayDemo values(2,'Carol','Taylor'); mysql> insert into SimulateArrayDemo values(3,'Bob','Smith'); mysql> insert into SimulateArrayDemo values(4,'David','Taylor'); mysql> insert into SimulateArrayDemo values(5,'John','Smith'); mysql> insert into SimulateArrayDemo values(6,'Mike','Taylor');
使用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'; 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)