简体   繁体   English

MySql-如何在两列中的两个值的组合上创建唯一约束

[英]MySql - how can you create a unique constraint on a combination of two values in two columns

I have a problem with creating index described in answer for this question: sql unique constraint on a 2 columns combination 我对此问题的答案中所述的创建索引有问题: 2列组合上的sql唯一约束

I am using MySql, and I received syntax error, my version of this query is as follows: 我正在使用MySql,并且收到语法错误,此查询的版本如下:

CREATE UNIQUE INDEX ON friends (LEAST(userID, friendID), GREATEST(userID, friendID));

LEAST and GREATEST functions are available in MySql, but maybe the syntax should be different? 在MySQL中可以使用LEAST和GREATEST函数,但是语法可能有所不同吗? I tried to make an ALTER TABLE version, but it does not worked as well. 我试图制作一个ALTER TABLE版本,但是效果不佳。

In MySQL, you can't use functions as the values for indexes. 在MySQL中,不能将函数用作索引值。

The documentation does not explicitly state this, however, it is a basic characteristic of an index to only support "fixed" data: 文档没有明确说明这一点,但是,它仅支持“固定”数据是索引的基本特征:

Indexes are used to find rows with specific column values quickly. 索引用于快速查找具有特定列值的行。 Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. 没有索引,MySQL必须从第一行开始,然后通读整个表以找到相关的行。

Generally, this "fixed" data is an individual column/field; 通常,此“固定”数据是单独的列/字段; with string-fields (such as varchar or text ) you can have a prefix-index and not the entire column. 使用字符串字段(例如varchartext ),您可以拥有一个前缀索引,而不是整个列。 Check out CREATE INDEX for more info on that. 查阅CREATE INDEX以获得更多信息。

The unique index that you're trying to create in you example will have a single record ever; 您要在示例中尝试创建的唯一索引将永远只有一条记录; that's not really a beneficial index since it doesn't help for searching the entire table. 这并不是真正有益的索引,因为它无助于搜索整个表。 However, if you index your table on userID, friendID , using the LEAST() and GREATEST() functions in a SELECT statement will be optimized thanks to the index itself, so it may be what you're after in this case. 但是,如果您在userID, friendID上对表建立索引,则由于有了索引本身,在SELECT语句中使用userID, friendID LEAST()GREATEST()函数将得到优化,因此在这种情况下可能就是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM