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

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

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