MySQL: Name primary key in CREATE TABLE statement

前端 未结 4 2009
醉梦人生
醉梦人生 2020-12-20 17:40

How do I set the name of a primary key when creating a table?

For example here I\'m trying to create a primary key with the name \'id\', but this is invalid SQL. Can

相关标签:
4条回答
  • 2020-12-20 18:11

    You shouldn't specify the column name when you specify the primary key column name directly inline with the column definition, so:

    CREATE TABLE IF NOT EXISTS `default_test` ( 
     `default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY  , 
     `default_test`.`name` LONGTEXT NOT NULL 
     );
    

    Alternativly you could do:

      CREATE TABLE IF NOT EXISTS `default_test` ( 
       `default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT , 
       `default_test`.`name` LONGTEXT NOT NULL ,
        PRIMARY KEY `default_test_id_pkey` (`id`)
       );
    
    0 讨论(0)
  • 2020-12-20 18:12

    http://dev.mysql.com/doc/refman/5.1/en/create-table.html

    [...] In MySQL, the name of a PRIMARY KEY is PRIMARY. [...]

    CREATE TABLE IF NOT EXISTS `default_test` (
        `default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT,
        `default_test`.`name` LONGTEXT NOT NULL,
        PRIMARY KEY (`id`)
    )
    
    0 讨论(0)
  • 2020-12-20 18:20

    You don't have to specify the column name again, because you already specified it as part of the current field definition - just say PRIMARY KEY.

    CREATE TABLE IF NOT EXISTS `default_test` (
        `id` SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `name` LONGTEXT NOT NULL
    )
    

    Alternatively, you can specify it separately later:

    CREATE TABLE IF NOT EXISTS `default_test` (
        `id` SMALLINT NOT NULL AUTO_INCREMENT,
        `name` LONGTEXT NOT NULL,
        PRIMARY KEY(`id`)
    )
    
    0 讨论(0)
  • 2020-12-20 18:22

    Alternatively and more widely supported:

    CREATE TABLE IF NOT EXISTS `default_test` (
     `default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT,
     `default_test`.`name` LONGTEXT NOT NULL,
     PRIMARY KEY (`id`)
    )
    

    UPDATE

    Based on the clarification, you could replace the last definition above with the following if you are to specify the index name:

    CONSTRAINT `pk_id` PRIMARY KEY (`id`)
    
    0 讨论(0)
提交回复
热议问题