【问题标题】:index uniq key does not seems to work索引唯一键似乎不起作用
【发布时间】:2013-11-13 20:25:17
【问题描述】:

我正在尝试为我的聊天发出一种好友请求,

所以我设置了一个名为cyb_user_friendlist的表

然后我放了一些这样的表格:

1   id_friendlist   int(11) AUTO_INCREMENT   
2   from            int(11)     
3   to          int(11)         
4   couple          varchar(11)
5   accept          int(11)     
6   block           int(11)

因此,对于每个朋友请求,都会在此表中插入发送者的 id 到 from 和接收者的 id 到 to,但是为了确保每对夫妇只有一个请求,我添加了一个名为 couple 的字段,其中有from 和 to 与垂直分隔符 | 的连接。该字段有一个 uniq 键,因为我想防止出现多条记录。

唯一的问题是它似乎不起作用,实际上我在这个字段中添加了我的 uniq 键和 id_friendlist 的主键,但它不起作用,我可以根据需要发送许多请求...

我的请求 $sql 如下:

$query = "INSERT INTO `cyb_users_friendlist` SET
            `from` = {$from},
            `to` = {$to},
            `couple` = '{$from}|{$to}'";

我真的不知道我哪里错了……

我们将不胜感激。

【问题讨论】:

  • 不确定这里的问题是什么
  • 问题是即使使用索引唯一键它也会插入重复条目...我也尝试使用插入忽略但它不起作用
  • 您不需要“情侣”,您可以在 2 个字段上添加唯一索引。更改表 YOUR TABLE NAME 添加唯一 unique ( from , to )
  • 你能发布show create table cyb_users_friendlist的输出吗?听起来您似乎没有正确创建唯一键。
  • REATE TABLE cyb_users_friendlist (id_friendlist int(11) NOT NULL AUTO_INCREMENT, from int(11) NOT NULL, to int(11) NOT NULL, couple varchar( 11) 非空,accept int(11) 默认空,block int(11) 非空默认 '0',主键 (id_friendlist),唯一键 id_friendlist (id_friendlist),唯一键couple (couple) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1

标签: php mysql sql indexing unique-key


【解决方案1】:

当您可以添加唯一索引时,为什么还要添加另一个连接两个字段的字段?

mysql combined unique keys

ALTER TABLE `YOUR TABLE` ADD UNIQUE `unique` ( `from` , `to` ) 

【讨论】:

  • 不,因为我需要有互惠的连接,所以如果有人给你发了,你不能发朋友请求,只回答前一个。
  • 那么你需要两个索引:dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html 否则我就是没有正确理解问题。
  • 否,因为如果我添加两个索引,这意味着一个用户只能发送一个好友请求,而不能向其他用户发送很多。
  • 现在知道了。然后只需使用索引来连接这两列并使该索引唯一。这将与创建 couple 列相同。否则……我不知道。
【解决方案2】:
 $query = "INSERT INTO `cyb_users_friendlist` SET
        `from` = $from,
        `to` = $to,
        `couple` = concat('$from','|','$to')'";

【讨论】:

  • 即使使用唯一键允许多条记录,我仍然有相同的结果
  • 但是当您回显查询时,它看起来还不错?
  • 是的,但它应该插入一次,现在我可以插入我想要的次数
猜你喜欢
  • 2019-02-14
  • 2018-07-30
  • 1970-01-01
  • 2012-06-25
  • 2023-03-07
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
相关资源
最近更新 更多