Computer >> Máy Tính >  >> Lập trình >> MySQL

Đặt kết quả của một truy vấn thành một biến trong MySQL?

Bạn có thể đặt kết quả của một truy vấn bằng lệnh select into. Cú pháp như sau.

select yourColumnName1 into @anyVariableName from yourTableName where yourColumnName2='anyValue';

Kiểm tra kết quả có trong biến hay không bằng cách sử dụng lệnh select. Cú pháp như sau -

select @anyVariableName;

Để hiểu cú pháp trên, trước tiên chúng ta hãy tạo một bảng. Truy vấn để tạo bảng như sau.

mysql> create table StudentInformation
-> (
-> StudentId int,
-> StudentName varchar(100),
-> StudentAge int
-> );
Query OK, 0 rows affected (0.62 sec)

Chèn một số bản ghi trong bảng bằng lệnh chèn. Truy vấn như sau.

mysql> insert into StudentInformation values(1,'John',23);
Query OK, 1 row affected (0.21 sec)

mysql> insert into StudentInformation values(2,'Adam',24);
Query OK, 1 row affected (0.17 sec)

mysql> insert into StudentInformation values(3,'Bob',21);
Query OK, 1 row affected (0.20 sec)

mysql> insert into StudentInformation values(4,'Carol',20);
Query OK, 1 row affected (0.17 sec)

mysql> insert into StudentInformation values(5,'Mike',25);
Query OK, 1 row affected (0.13 sec)

Hiển thị tất cả các bản ghi từ bảng bằng cách sử dụng câu lệnh select. Truy vấn như sau.

mysql> select *from StudentInformation;

Sau đây là kết quả.

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1         | John        | 23         |
| 2         | Adam        | 24         |
| 3         | Bob         | 21         |
| 4         | Carol       | 20         |
| 5         | Mike        | 25         |
+-----------+-------------+------------+
5 rows in set (0.00 sec)

Đây là truy vấn để đặt kết quả của truy vấn thành một biến.

mysql> select StudentAge into @yourAge from StudentInformation where StudentName='Adam';
Query OK, 1 row affected (0.03 sec)

Kiểm tra những gì được lưu trữ trong biến @yourAge. Truy vấn như sau.

mysql> select @yourAge;

Sau đây là kết quả hiển thị tuổi của Student Adam.

+----------+
| @yourAge |
+----------+
| 24       |
+----------+
1 row in set (0.00 sec)