Home > Database > Mysql Tutorial > body text

How to assign query results to variables in mysql

青灯夜游
Release: 2022-01-24 18:14:21
Original
16469 people have browsed it

Mysql method of assigning query results to variables: 1. Use the "DECLARE variable name type [DEFAULT default value];" statement to create a variable; 2. Use "SELECT field name INTO variable name FROM table name WEHRE query "Condition;" statement assigns the query results to variables.

How to assign query results to variables in mysql

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

Mysql method of assigning query results to variables

1. Create variables

MySQL You can use the DECLARE keyword to define variables. The basic syntax is as follows:

DECLARE 变量名 类型 [DEFAULT 默认值]
Copy after login

If the DEFAULT clause is omitted, the default value is NULL.

Example: Define the variable my_sql, the data type is INT type

DECLARE my_sql INT;
Copy after login

2. Assign the query results to the variable

You need to use SELECT ..INTO statement, its basic syntax is as follows:

SELECT col_name [...] INTO var_name[,...]
FROM table_name WEHRE condition
Copy after login

Among them:

  • col_name parameter represents the query field name;

  • ## The
  • #var_name parameter is the name of the variable; the

  • table_name parameter refers to the name of the table; the

  • condition parameter refers to the query condition.

Note: When assigning query results to variables, the query statement can only return a single row.

Example: Query the record with id 2 from the tb_student table, and assign the id value of the record to the variable my_sql. The SQL statement is as follows:

SELECT id INTO my_sql FROM tb_student WEHRE id=2;
Copy after login
[Related recommendations:

mysql video tutorial]

The above is the detailed content of How to assign query results to variables in mysql. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!