MySQL表注释跨越多行

时间:2018-10-02 23:26:49

标签: mysql sql

在MySQL中创建表时,我们可以指定注释。

有人知道一种将字符串传递到COMMENT =的方法吗?

我尝试使用由CONCAT生成的局部变量,还尝试使用诸如'foo ' 'bar ' 'baz'这样的字符串文字语法

例如:

CREATE TABLE foo (
    id INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (id)
) COMMENT = 'some really long string that we want to span multiple lines instead of being limited to a single line';

2 个答案:

答案 0 :(得分:0)

如果要嵌入换行符,请使用\n

CREATE TABLE `foo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='some really long string\nthat we want to span multiple lines\ninstead of being limited to a single line'

如果您使用SHOW CREATE TABLE查看注释,注释仍将显示为一个长字符串。该语句返回重新创建表所需的确切语法,因此,如果需要使用\n来放置换行符,它将显示该内容。

但是,如果您从INFORMATION_SCHEMA查询表元数据,则可以将换行符输出为实际的换行符:

mysql> select * from information_schema.tables where table_name='foo'\G
*************************** 1. row ***************************
  TABLE_CATALOG: def
   TABLE_SCHEMA: test
     TABLE_NAME: foo
     TABLE_TYPE: BASE TABLE
         ENGINE: InnoDB
        VERSION: 10
     ROW_FORMAT: Compact
     TABLE_ROWS: 0
 AVG_ROW_LENGTH: 0
    DATA_LENGTH: 16384
MAX_DATA_LENGTH: 0
   INDEX_LENGTH: 0
      DATA_FREE: 0
 AUTO_INCREMENT: 1
    CREATE_TIME: 2018-10-02 23:37:57
    UPDATE_TIME: NULL
     CHECK_TIME: NULL
TABLE_COLLATION: utf8mb4_general_ci
       CHECKSUM: NULL
 CREATE_OPTIONS: 
  TABLE_COMMENT: some really long string
that we want to span multiple lines
instead of being limited to a single line

答案 1 :(得分:0)

要与@BillKarwin的答案一起使用:如果要使用多行内容来创建注释,请这样做:

CREATE TABLE foo
(
    foo_id int primary key auto_increment,
    foo_name varchar(255)
)
COMMENT = 'this is a 
multi-line comment'

不幸的是,您似乎无法在注释构造中进行任何类型的串联(将实际DDL分为多行,而实际DDL中没有换行)。例如,这不可能是可能的:

CREATE TABLE foo(foo_id INT PRIMARY KEY AUTO_INCREMENT) 
COMMENT = CONCAT('multi-line', 
    ' comment'

当然,如果要通过客户端语言(PHP或Python或其他方式)访问MySQL,则可以根据需要构造字符串:

ddl = 
'''
CREATE TABLE `foo` (
    `foo_id` int PRIMARY KEY AUTO_INCREMENT
)''' + \ 
'''COMMENT='This is a multi-line ''' + \
'''comment''''