是否可以使用预准备语句在MySQL中创建表?我有以下语句,它使用第二个表中的条件从一个表中选择列,并希望创建一个包含结果的表:
SET @sql = (
SELECT GROUP_CONCAT(COLUMN_NAME) FROM
(SELECT DISTINCT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='mpi_install') a
JOIN display_data
ON display_data.display_data_name = a.column_name
WHERE display_data.display_summary = "1"
AND display_data.phase_name="mpi_install"
);
SET @query = CONCAT('SELECT ', @sql, 'FROM mpi_install');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
此输出是(带伪造的测试数据):
+---------------+-------------------+-------------+---------------------+
| http_username | platform_hardware | test_result | start_timestamp |
+---------------+-------------------+-------------+---------------------+
| name1 | platform1 | result1 | 0000-00-00 00:00:00 |
| name2 | platform2 | result2 | 0000-00-00 00:00:00 |
| name3 | platform3 | result3 | 0000-00-00 00:00:00 |
| name4 | platform4 | result4 | 0000-00-00 00:00:00 |
| name5 | platform5 | result5 | 0000-00-00 00:00:00 |
| name6 | platform6 | result6 | 0000-00-00 00:00:00 |
| name7 | platform7 | result7 | 0000-00-00 00:00:00 |
| name8 | platform8 | result8 | 0000-00-00 00:00:00 |
+---------------+-------------------+-------------+---------------------+
原始表mpi_install包含更多列,display_data定义将从此表和其他表中显示哪些列。
答案 0 :(得分:0)
使用它:
SET @query = CONCAT('CREATE TABLE `name` AS SELECT ', @sql, 'FROM mpi_install');