简体   繁体   English

(MySQL)主键带有2个相同的外键

[英](MySQL) Primary key w/ 2 same foreign keys

I have 3 tables: 我有3张桌子:

Users: _id_, username
Movies: _id_, title
Friends: _#id1, #id2_, accepted

I'm with InnoDB, everything is working like that. 我在InnoDB上,一切都在那样工作。 But, even if friends' primary-key is (users.id, users.id), 2 rows like that are accepted by MySQL: 但是,即使朋友的主键是(users.id,users.id),MySQL也接受类似的2行:

1) (1, 2)
2) (2, 1)

Is there a way to consider these 2 rows as a duplicate key for MySQL ? 有没有办法将这两行视为MySQL的重复键?
Thanks for your help. 谢谢你的帮助。

I cannot think of any way to let MySQL alone solve this problem. 我想不出任何办法让MySQL独自解决这个问题。 I would use GREATEST ( http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_greatest ) and LEAST ( http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_least ) for any insert/update on this table: 我会使用GREATEST( http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_greatest )和LEAST( http://dev.mysql.com/doc/refman/5.0/ zh_cn / comparison-operators.html#function_least )以获取对此表的任何插入/更新:

INSERT INTO friends (LEAST(_#id1, _#id2), GREATEST(_#id1, _#id2));

So you will never get (2, 1) and always have (1, 2). 因此,您永远不会得到(2,1),而总会有(1,2)。

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

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