• 请不要在回答技术问题时复制粘贴 AI 生成的内容
littlepython
V2EX  ›  程序员

mysql 设置自增必须是主键吗?

  •  
  •   littlepython · Dec 12, 2020 · 4537 views
    This topic created in 2165 days ago, the information mentioned may be changed or developed.

    早上写了个语句 id 自增但不是主键一直报错 语句:create table student(id INT AUTO_INCREMENT, name VARCHAR(200) NOT NULL) ENGINE=INNODB CHARSET=utf8; 报错是:1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key

    mysql 版本是 8.0.20-0ubuntu0.20.04.1

    网上查询有的说可以 有的不可以,有点迷

    7 replies  •  2020-12-13 14:52:40 +08:00
    hbolive
    hbolive
    Dec 12, 2020
    1
    错误提示必须是 key,不是 PRIMARY KEY 吧
    Xia
    Xia
    Dec 12, 2020
    2
    什么场景会用到非主键要自增
    littlepython
    littlepython
    OP
    Dec 12, 2020
    3
    @Xia 只是自己随便写的 发现了这个问题
    littlepython
    littlepython
    OP
    Dec 12, 2020
    4
    @hbolive 额,要有 key 才能自增?
    dorothyREN
    dorothyREN
    Dec 12, 2020
    6
    pg 就香了,定义个序列,想在哪用就在哪用
    neoblackcap
    neoblackcap
    Dec 13, 2020
    7
    根据以前书上的说法,InnoDB 采取存储为 B 树,那么最好就是用整型的作为主键,自不自增没所谓。
    然后哪怕主键是整型,你完全可以定义一个逻辑主键,并使用字符串作为该栏的数据类型。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2237 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 14:29 · PVG 22:29 · LAX 06:29 · JFK 09:29
    ♥ Do have faith in what you're doing.