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

Lưu trữ giá trị từ một câu lệnh MySQL SELECT vào một biến?


Trước tiên, chúng ta hãy tạo một bảng -

mysql> create table DemoTable631 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,StudentName varchar(100)
);
Query OK, 0 rows affected (0.83 sec)

Chèn một số bản ghi vào bảng bằng lệnh chèn -

mysql> insert into DemoTable631(StudentName) values('John Smith');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable631(StudentName) values('Adam Smith');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable631(StudentName) values('David Miller');
Query OK, 1 row affected (0.16 sec)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select -

mysql> select *from DemoTable631;

Điều này sẽ tạo ra kết quả sau -

+-----------+--------------+
| StudentId | StudentName  |
+-----------+--------------+
|         1 | John Smith   |
|         2 | Adam Smith   |
|         3 | David Miller |
+-----------+--------------+
3 rows in set (0.00 sec)

Sau đây là truy vấn để lưu trữ giá trị từ lựa chọn đến một biến -

mysql> set @fullName=(select StudentName from DemoTable631 where StudentId=2);
Query OK, 0 rows affected (0.00 sec)

Bây giờ bạn có thể hiển thị giá trị của một biến -

mysql> select @fullName;

Điều này sẽ tạo ra kết quả sau -

+------------+
| @fullName  |
+------------+
| Adam Smith |
+------------+
1 row in set (0.00 sec)