要在MySQL中设置变量,您需要使用SET命令。以下是语法:
set @yourVariableName:=yourValue; select *from yourTableName where yourColumnName=@yourVariableName;
让我们首先创建一个表:
mysql> create table DemoTable ( Id int, FirstName varchar(20), LastName varchar(20) );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable values(10,'Carol','Taylor'); mysql> insert into DemoTable values(20,'John','Doe'); mysql> insert into DemoTable values(30,'John','Smith'); mysql> insert into DemoTable values(40,'David','Miller');
以下是使用select命令显示表中记录的查询:
mysql> select *from DemoTable;
这将产生以下输出:
+------+-----------+----------+ | Id | FirstName | LastName | +------+-----------+----------+ | 10 | Carol | Taylor | | 20 | John | Doe | | 30 | John | Smith | | 40 | David | Miller | +------+-----------+----------+ 4 rows in set (0.00 sec)
现在让我们看看如何在MySQL中设置用户定义的变量:
mysql> set @myId:=30; mysql> select *from DemoTable where Id=@myId;
这将产生以下输出
+------+-----------+----------+ | Id | FirstName | LastName | +------+-----------+----------+ | 30 | John | Smith | +------+-----------+----------+ 1 row in set (0.00 sec)