mysql列名不允许空格

时间:2017-07-04 12:27:36

标签: php mysql

我有一张表testnew

    +---------------------+
    | v_id | name         | 
    +---------------------+
    |   1  | Productivity | 
    |   2  | Work Quality | 
    |   3  | Knowldge     |
    |   4  | Comm know    | 
    +------+--------------+

由admin添加,我将创建另一个表(预期)

    +---------------+--------------+------------+----------+
    |  Productivity |Work Quality  | Knowldge   |Comm know |
    +------------+-----------------+------------------------
    |                                                      |
    |                                                      |  
    |                                                      |
    |                                                      |
    +------------+-----------------------------------------+

查询:

SELECT
  CONCAT(
    'CREATE TABLE new (',
    GROUP_CONCAT(DISTINCT
      CONCAT(name, ' VARCHAR(50)')
      SEPARATOR ','),
    ');')
FROM
  testnew
INTO @sql;

PREPARE stmt FROM @sql;
EXECUTE stmt;

Work QualityComm know有空格,所以无法输出。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

我反对在列名中加入特殊字符。但如果必须,请使用MySQL转义字符(反引号)或双引号:

SELECT CONCAT('CREATE TABLE new (',
              GROUP_CONCAT(DISTINCT CONCAT('`', name, '` VARCHAR(50)')
                           SEPARATOR ','),
              ');')
       FROM testnew
INTO @sql;

注意:CONCAT()中的GROUP_CONCAT()是多余的。一个鲜为人知的事实是GROUP_CONCAT()有多个参数:

SELECT CONCAT('CREATE TABLE new (',
              GROUP_CONCAT(DISTINCT '`', name, '` VARCHAR(50)'
                           SEPARATOR ','),
              ');')
       FROM testnew
INTO @sql;