首先,您需要准备查询,然后需要执行PREPARED语句以动态选择MySQL中的列。
让我们首先创建一个表-
mysql> create table DemoTable ( EmployeeName varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('John Doe');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+--------------+ | EmployeeName | +--------------+ | John Doe | +--------------+ 1 row in set (0.00 sec)
现在让我们动态地选择MySQL中的一列-
mysql> set @dynamicQuery=CONCAT("SELECT ", (SELECT "EmployeeName from DemoTable")); mysql> select @dynamicQuery; +---------------------------------------+ | @dynamicQuery | +---------------------------------------+ | SELECT EmployeeName from DemoTable | +---------------------------------------+ 1 row in set (0.00 sec) mysql> prepare myStatement from @dynamicQuery; Statement prepared mysql> execute myStatement;
这将产生以下输出-
+--------------+ | EmployeeName | +--------------+ | John Doe | +--------------+ 1 row in set (0.00 sec)