2012-03-08 42 views
1

我有3個表:(MySQL的)主鍵W/2相同的外鍵

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

我與InnoDB的,一切都是那樣工作。但是,即使朋友主鍵(users.id,users.id),2行像被MySQL接受:

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

有沒有考慮這些2行作爲一個重複鍵的方式MySQL?
感謝您的幫助。

回答

1

我想不出有什麼辦法讓MySQL獨自解決這個問題。我會用任何插入/更新GREATEST(http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_greatest)和LEAST(http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_least)本表:

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

所以,你將永遠不會得到(2,1)和總是(1,2)。

+1

謝謝,這很好。 – Max13 2012-03-09 10:43:19