简体   繁体   中英

mysql query about create table ddl format

I am a mysql newbie. I have a question about the right thing to do for create table ddl. Up until now I have just been writing create table ddl like this...

CREATE TABLE file (
    file_id mediumint(10) unsigned NOT NULL AUTO_INCREMENT,
    filename varchar(100) NOT NULL,
    file_notes varchar(100) DEFAULT NULL,
    file_size mediumint(10) DEFAULT NULL,
    file_type varchar(40) DEFAULT NULL,
    file longblob DEFAULT NULL,
  CONSTRAINT pk_file PRIMARY KEY (file_id)
);

But I often see people doing their create table ddl like this...

CREATE TABLE IF NOT EXISTS `etags` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `item_code` varchar(100) NOT NULL,
  `item_description` varchar(500) NOT NULL,
  `btn_type` enum('primary','important','success','default','warning') NOT NULL DEFAULT 'default',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

A few questions...

  1. What difference do the quotes around the table name and column names make?

  2. Is it good practice to explicitly declare the engine and character set? What engine and character sets are used by default?

thanks

  1. There's no difference. Identifiers (table names, column names, et al.) must be enclosed in the backticks if they contain special characters or are reserved words. Otherwise, the backticks are optional.

  2. Yes, it's good practice, for portability to other systems. If you re-create the table, having the storage engine and character set specified explicitly in the CREATE TABLE statement means that your statement won't be dependent on the settings of the default_character_set and default-storage-engine variables (these may get changed, or be set differently on another database.)


You can get your table DDL definition in that same format using the SHOW CREATE TABLE statement, eg

SHOW CREATE TABLE `file`

The CREATE TABLE DDL syntax you are seeing posted by other users is typically in the format produced as output of this statement. Note that MySQL doesn't bother with checking whether an identifier contains special characters or reserved words (to see if backticks are required or not), it just goes ahead and wraps all of the identifiers in backticks.

  1. With backticks, reserved words and some special characters can be used in names.
    It's simply a safety measure and many tools automatically add these.

  2. The default engine and charset can be set in the servers configuration.
    They are often (but not always) set to MyISAM and latin1 .

Personally, I would consider it good practice to define engine and charset, just so you can be certain what you end up with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM