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

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

  •  
  •   353943780 · Apr 2, 2020 · 2951 views
    This topic created in 2407 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
    b821025551b
    Apr 2, 2020
    1
    看不懂,a 都是字段名了,怎么去==1
    353943780
    353943780
    OP
    Apr 2, 2020
    2
    @b821025551b 可能是我描述不清楚,如果数据记录中 a 字段值为 1 的时候,与字段 b 、c 联合为唯一
    scriptB0y
    scriptB0y
    Apr 2, 2020❤️2
    3
    有一种索引叫做 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
    lysS
    Apr 2, 2020
    4
    你把那两中情况分成两个表嘛
    rrfeng
    rrfeng
    Apr 2, 2020
    5
    mongodb 也支持 partial index

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

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

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