您可以使用 MySQL 用户变量来记住结果,而无需将它们存储在客户端的临时变量中。(参见 第 11.4 节,“用户定义的变量”。)You can employ MySQL user variables to remember results without having to store them in temporary variables in the client. (See Section 11.4, “User-Defined Variables”.)
例如,要查找价格最高和最低的文章,你可以这样做:For example, to find the articles with the highest and lowest price you can do this:
mysql>SELECT @min_price:=MIN(price),@max_price:=MAX(price) FROM shop;mysql>SELECT * FROM shop WHERE price=@min_price OR price=@max_price;+---------+--------+-------+ | article | dealer | price | +---------+--------+-------+ | 0003 | D | 1.25 | | 0004 | D | 19.95 | +---------+--------+-------+
也可以将数据库对象(如表或列)的名称存储在用户变量中,然后在 SQL 语句中使用该变量;然而,这需要使用预处理语句。有关更多信息,请参阅第 15.5 节,“预处理语句”。It is also possible to store the name of a database object such as a table or a column in a user variable and then to use this variable in an SQL statement; however, this requires the use of a prepared statement. See Section 15.5, “Prepared Statements”, for more information.