SQL如何用唯一键创建表?

时间:2018-06-11 00:19:38

标签: mysql sql ddl

使用此定义创建课程表(尝试使用多行SQL语句):

+---------+---------------------+------+-----+---------+----------------+
| Field   | Type                | Null | Key | Default | Extra          |
+---------+---------------------+------+-----+---------+----------------+
| id      | int(3) unsigned     | NO   | PRI | NULL    | auto_increment |
| title   | varchar(255)        | NO   | UNI | NULL    |                |
| credits | tinyint(2) unsigned | NO   |     | 1       |                |

我在尝试创建表时遇到错误,这就是我所拥有的:

CREATE TABLE courses 
(
    id int(3)  unsigned NOT NULL AUTO_INCREMENT,
    title varchar(255) NOT NULL UNIQUE,
    credits tinyint(2) unsigned NOT NULL DEFAULT 1;

2 个答案:

答案 0 :(得分:2)

错误:

Incorrect table definition; there can be only one auto column and it must be defined as a key

更正SQL句子:

CREATE TABLE courses (
id      int(3) unsigned   primary key  NOT NULL AUTO_INCREMENT,
title   varchar(255)        NOT NULL UNIQUE,
credits tinyint(2) unsigned NOT NULL DEFAULT 1);

你的句子丢失了primary key

答案 1 :(得分:2)

两个错误:

  • auto_increment列必须是MySQL中的主键。

  • 您需要使用)结束SQL语句。

此SQL有效:

CREATE TABLE courses (
  id int(3)  unsigned primary key NOT NULL AUTO_INCREMENT,
  title varchar(255) NOT NULL UNIQUE,
  credits tinyint(2) unsigned NOT NULL DEFAULT 1
);