【问题标题】:Can only one unique constraint be applied on the column while others are defined?是否只能对列应用一个唯一约束而定义其他约束?
【发布时间】:2016-04-20 10:01:33
【问题描述】:

假设我们必须保留人们的投票,可以来自用户或访客:

CREATE TABLE votes (
  to_user_id INT UNSIGNED NOT NULL,
  from_user_id INT UNSIGNED,
  from_ip_address INT UNSIGNED
)

对于用户投票,我们要应用唯一约束 (to_user_id, from_user_id),对于访客,要应用约束 (to_user_id, from_ip_address)

不存在同时应用的唯一索引的组合不会破坏以下任何一项:投票的唯一性以及具有相同 IP 地址的不同用户的投票能力。

有什么好的解决办法吗?

【问题讨论】:

    标签: mysql sql database database-design


    【解决方案1】:

    你可以改变数据结构:

    CREATE TABLE Votes (
        VoteId int unsigned primary key,
        UserId int unsigned not null,
        IpAddress int unisgned,
        Which enum('from', 'to'),
        constraint unq_Votes_UserId_IpAddress_Which unique (UserId, IpAddress, Which)
    );
    

    请注意,我添加了一个主键,这对于外键引用、识别单行和维护插入的顺序非常方便。

    【讨论】:

    • 我们如何通过这种结构了解哪个用户投票给了哪个用户?
    • @alain_morel 。 . .您必须查看which 列以确定方向。
    【解决方案2】:

    最终我找到了一个可以接受的解决方案:

    CREATE TABLE votes (
      vote_id INT UNSIGNED AUTO_INCREMENT,
      to_user_id INT UNSIGNED NOT NULL,
      from_user_id INT UNSIGNED,
      from_user_ip INT UNSIGNED,
      from_guest_ip INT UNSIGNED,
      PRIMARY KEY (vote_id),
      UNIQUE INDEX (to_user_id, from_user_id),
      UNIQUE INDEX (to_user_id, from_guest_ip)
    );
    
    INSERT INTO votes (to_user_id, from_user_id, from_user_ip) VALUES (1, 2, 255), (1, 3, 255);
    INSERT INTO votes (to_user_id, from_guest_ip) VALUES (1, 255);
    

    【讨论】:

      猜你喜欢
      • 2011-10-02
      • 2021-03-26
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 2011-06-17
      相关资源
      最近更新 更多