MySQL column-level constraints and table-level constraints

First, the six constraints

  • NOT NULL non-empty
  • PRIMARY KEY primary key
  • UNIQUE unique
  • CHECK check constraint, MySQL does not support, syntax error but there was no effect
  • FOREIGN KEY foreign key. Two limit table relationships, introduced from the normal value table foreign key constraints, the introduction of the value of a column in the primary table, to ensure that the value of this field must be derived from the primary table associated with the table in the column
  • DEFAULT default value / setpoint system

Second, the table level and column-level constraint definition:

  • Table-level constraints: constraints on the establishment of multiple data columns, called table-level constraints can only table-level constraints after the column definition statement
  • Column-level constraints: constraints on the establishment of a data column, called a column-level constraint column-level constraints may be declared in the column definition, can also be a statement after the column definition
 ps: the word is simple to understand for column-level constraints are single row, table-level constraints for the entire table, so corollary
Six column-level constraints in the constraint can be used, but no effect of foreign keys (foreign key constraint is a relationship between two tables)
Obviously, non-empty by default, and can not be used at the table level constraints

Third, the timing of adding constraints:

  • When you create a table:

  # Create the main table, the foreign key experiment

  CREAT  TABLE  IF  NOT  EXISTS  major(

        id INT,

        major_name varchar(20)

  );

  # Created from a table, table-level experiment / column-level constraint

  CREAT  TABLE  IF  NOT  EXISTS  students(

        # Add a table-level constraints, can be added directly after the type

        id INT PRIMARY KEY,

        student_name VARCHAR(20),

        sex CHAR(1),

        age INT DEFAULT 18,

        majorid INT,

      

        # Add a table-level constraints, added directly after the end of the column is created

        CONSTRAINT pk PRIMARY KEY (id). # Primary key, used to name the constraint, may be applied without

        CONSTRAINT fk_student_majory FOREIGN KEY(majorid) REFERENCES major(id)#外键

  );

  • When modify the table:

  # Add a non-empty, the other column-level constraints can follow this method

  ALTER  TABLE  students  MODIFY  COLUMN  student_name  VARCHAR(20)  NOT  NULL;  

  # Add foreign key, the other table-level constraints may be added using the same procedure
   ALTER  TABLE  students ADD  FOREIGN  KEY(majorid)  REFERENCES  major(id) ;
 

Guess you like

Origin www.cnblogs.com/WIFI-365/p/11593416.html