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

新菜鸟请问各位大佬 MySQL 能不能字段等于某个值才建立唯一索引

  •  
  •   353943780 · Apr 2, 2020 · 2541 views
    This topic created in 2248 days ago, the information mentioned may be changed or developed.

    例如:

    a / b / c 都是字段名

    (a = 1) + b + c 是唯一索引

    (a != 1) + b + c 可重复

    6 replies    2020-04-03 09:09:35 +08:00
    b821025551b
        1
    b821025551b  
       Apr 2, 2020
    看不懂,a 都是字段名了,怎么去==1
    353943780
        2
    353943780  
    OP
       Apr 2, 2020
    @b821025551b 可能是我描述不清楚,如果数据记录中 a 字段值为 1 的时候,与字段 b 、c 联合为唯一
    scriptB0y
        3
    scriptB0y  
       Apr 2, 2020   ❤️ 2
    有一种索引叫做 partial index,可以根据条件建立索引。你这种情况可以

    create unique index unique_b_c_if_a_is_one on partial_index(b,c) where a='1';

    然后再创建一个索引

    create index unique_b_c_if_a_not_one on partial_index(b,c) where a!='1';

    就可以满足你的需求。但是据我所知 postgres ( https://www.postgresql.org/docs/9.3/indexes-unique.html ) 和 SQL Server 支持这种索引,mysql 目前应该不支持。

    不知道有没有其他方案哈。
    lysS
        4
    lysS  
       Apr 2, 2020
    你把那两中情况分成两个表嘛
    rrfeng
        5
    rrfeng  
       Apr 2, 2020
    mongodb 也支持 partial index

    拆一下表吧。或者另外加逻辑去重。
    MonoLogueChi
        6
    MonoLogueChi  
       Apr 3, 2020   ❤️ 1
    不清楚 mysql 有没有这种操作,但是我知道 postgresql 有这样的索引,叫做 Partial Indexes,

    CREATE INDEX xxx_index ON table1(col1) WHERE col2 is not true;

    mysql 我用的不多,不太清楚有没有这种东西,你可以顺着这个思路查一下
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2678 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 01:23 · PVG 09:23 · LAX 18:23 · JFK 21:23
    ♥ Do have faith in what you're doing.