每个字段上的MySQL CONCAT都没有明确地这样做

时间:2015-08-31 13:10:04

标签: mysql csv concatenation

我有一个脚本,它生成一个带有MySQL查询结果的CSV文件。我遇到的最初问题是,Excel将条目000123(00)解释为1230。我按照$mod回答解决了这个问题。

现在,如果我的SELECT如下:

SELECT employee.id,
       employee.access_code,
       employee.contact_number,
       employee.buzzer_number
FROM ...

我必须将其更改为:

SELECT CONCAT('\"=\"\"', employee.id, '\"\"\"') AS id,
       CONCAT('\"=\"\"', employee.access_code, '\"\"\"') AS access_code,
       CONCAT('\"=\"\"', employee.contact_number, '\"\"\"') AS contact_number,
       CONCAT('\"=\"\"', employee.buzzer_number, '\"\"\"') AS buzzer_number
FROM ...

对许多领域而言,这似乎很笨拙。有没有一种方法可以用"=""[value]"""包裹每个字段而不在SELECT子句中明确地这样做?

1 个答案:

答案 0 :(得分:1)

这是您搜索的内容

SELECT
  "tmp",                    -- Databasename
  "statistics",             -- Tablename
  "CONCAT( '\"=\"\"', ",    -- Pre Field
  ", \'\"\"\"\' ",          -- POST FIELD
  "id"                      -- BLOCKED Fields sep with comma

  INTO @DB, @TABLE,@PRE,@POST,@BLOCKED;


SELECT
  CONCAT('SELECT ', @BLOCKED , ',\n',
  GROUP_CONCAT(
    CONCAT(
        @PRE,
        COLUMN_NAME,
        @POST,
        ') AS ' ,
        COLUMN_NAME
    )
  SEPARATOR ',\n') ,
  '\n FROM ', @DB, '.', @TABLE)  
  FROM information_schema.COLUMNS WHERE TABLE_SCHEMA =  @DB AND TABLE_NAME = @TABLE 
  INTO @SQL1;

SELECT @SQL1;  -- only to review the Query

PREPARE stmt FROM @SQL1;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;