如何创建一个具有唯一键的表?

6yjfywim  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(662)

使用此定义创建课程表(请尝试使用多行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;
ux6nzvsh

ux6nzvsh1#

两个错误:
这个 auto_increment 列必须是mysql中的主键。
您需要用一个 ) .
此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
);
9gm1akwq

9gm1akwq2#

错误: 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 .

相关问题