Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Dùng MySQL CONCAT() tạo tên cột cho truy vấn

Để tạo tên cột động cho truy vấn, dùng biến user-defined với SET và CONCAT.

Cú pháp:

SET @anyVariableName := (    SELECT CONCAT    (       "SELECT",    GROUP_CONCAT(CONCAT("\n 1 as ", COLUMN_NAME) SEPARATOR ','), "\n FROM DUAL")    FROM INFORMATION_SCHEMA.COLUMNS    WHERE TABLE_NAME= 'yourTableName' );

Sau đó PREPARE, EXECUTE, DEALLOCATE PREPARE.

Demo: Tạo bảng ConcatenationWithUserDefinedVariable (Id, User_Id).

Tạo biến @q chứa câu SELECT động:

mysql> set @q := ( select concat( "select", group_concat(concat("\n 1 as ", column_name) separator ','), "\nfrom dual") from information_schema.columns where table_name = 'ConcatenationWithUserDefinedVariable');

PREPARE và EXECUTE:

mysql> prepare stmt from @q; mysql> execute stmt;
+----+---------+ | Id | User_Id | +----+---------+ |  1 | 1 | +----+---------+ 1 row in set (0.00 sec)

DEALLOCATE:

mysql> deallocate prepare stmt;