2012-02-20 97 views
2

場景:多對多關係。在MySQL/PHP中查找和存儲數據庫關係

表有2列:用戶名和UserChoiche

我存儲用戶的喜好逐一每排。 (這是最有效的方法是什麼?)

例子:

UserID   UserChoiche 

mark                             anna
mark                             paul
mark                             john
john                             mark

在這個例子中選擇了標記3個用戶,和John選擇了1個用戶。

約翰和馬克選擇了彼此,我需要PHP來找到這個數據庫關係。

// PHP的MySQL查詢,其選擇一個指定的用戶的所有choiches(在這種情況下標記)
SELECT UserChoiche from exampletable WHERE UserID mark

//找到匹配
??
這裏是我的問題:我正在尋找最簡單和最有效的方式來處理這個問題!

也許這樣嗎? (它可以工作,但我不能寫一個MySQL聲明,對我來說太複雜!)
If Userchoice of previous query (in this case it would return anna paul and john) EQUALS any Userid in the table (in this case john) AND that Userid has a Userchoiche with the value of the UserID from the previous query (in this example 4th row)
然後我們有一個匹配

//如果找到匹配,然後採取用戶名和UserChoiche並將它們存儲到變量,我會用它來進行一些通知(可以有很多比賽,所以也許使用數組?)

+0

這聽起來像你正在尋找一個自我加入。看看這個問題:http://stackoverflow.com/questions/1284441/how-does-a-mysql-self-join-work – 2012-02-20 22:23:15

回答

5
SELECT t1.UserID, t2.UserID 
FROM table t1, table t2 
WHERE t1.UserID = t2.UserChoiche 
    AND t2.UserID = t1.UserChoiche 

這應該吐出的是選擇對方兩個。我們基本上加入表格以找到彼此的關係

2

以下是返回匹配mark的用戶的查詢。鑑於上述數據,它會返回john

SELECT p2.UserID 
FROM preferences p1 
JOIN preferences p2 
ON p2.UserID = p1.UserChoice 
AND p1.UserChoice = p2.UserID 
WHERE p1.UserID = 'mark' 
+0

我喜歡它,它似乎工作(測試仍在進行中),但可以你請澄清p1和p2是什麼? – 2012-02-20 22:33:33

+0

好吧,現在我想出了一切,它完美的工作!謝謝! – 2012-02-21 01:48:54

+0

'p1'和'p2'是[表別名](http://dev.mysql.com/doc/refman/5.0/en/select.html)。編寫查詢的另一種方法是'FROM preferences AS p1',這使得它更加明顯,它是一個別名。別名允許我用兩個不同的縮寫名稱引用同一張表。 – 2012-02-21 14:04:06

相關問題