MySQL 查询中输入参数(变量)的语法是什么?
mysqlmysqli database
要在 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)