MySQL 查询中输入参数(变量)的语法是什么?
要在 MySQL 中设置变量,你需要使用 SET 命令。语法如下
set @yourVariableName:=yourValue; select *from yourTableName where yourColumnName=@yourVariableName;
我们先创建一个表
mysql> create table DemoTable ( Id int, FirstName varchar(20), LastName varchar(20) ); Query OK, 0 rows affected (0.83 sec)
这是使用 insert 命令在表中插入一些记录的查询
mysql> insert into DemoTable values(10,'Carol','Taylor'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(20,'John','Doe'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(30,'John','Smith'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(40,'David','Miller'); Query OK, 1 row affected (0.18 sec)
这是使用 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; Query OK, 0 rows affected (0.00 sec) mysql> select *from DemoTable where Id=@myId;
这将产生以下输出
+------+-----------+----------+ | Id | FirstName | LastName | +------+-----------+----------+ | 30 | John | Smith | +------+-----------+----------+ 1 row in set (0.00 sec)
广告