2010-11-07 70 views
0

我希望用戶只能發送給他們的朋友。 現在我有這樣的:SQL:只顯示朋友

$qur = mysql_query(" 
SELECT users.id, users.firstname, users.lastname, 
(users.firstname = '$firstname' AND users.lastname = '$lastname') AS full FROM users 
WHERE 
(users.firstname = '$firstname' AND users.lastname='$lastname') 
OR (users.firstname LIKE '$firstname%' AND users.lastname LIKE '$lastname%') 
OR users.firstname LIKE '$firstname%' OR users.lastname LIKE '$firstname%' 
ORDER BY (users.firstname = '$firstname' AND users.lastname='$lastname') DESC") or die(mysql_error()); 

這說明在那些像$姓名的用戶每個人,$姓氏

現在我試圖讓只能選擇user's朋友$名字,姓氏$,加入這樣的:

INNER JOIN users_friends ON users.id=users_friends.uID 
WHERE users_friends.bID='$USER' AND users_friends.type = '$typeUsers' AND 

所以它得到了這樣的:

$qur = mysql_query(" 
SELECT users.id, users.firstname, users.lastname, 
(users.firstname = '$firstname' AND users.lastname = '$lastname') AS full FROM users 
    INNER JOIN users_friends ON users.id=users_friends.uID 
WHERE users_friends.bID='$USER' AND users_friends.type = '$typeUsers' AND 
(users.firstname = '$firstname' AND users.lastname='$lastname') 
OR (users.firstname LIKE '$firstname%' AND users.lastname LIKE '$lastname%') 
OR users.firstname LIKE '$firstname%' OR users.lastname LIKE '$firstname%' 
ORDER BY (users.firstname = '$firstname' AND users.lastname='$lastname') DESC") or die(mysql_error()); 

如果存在共4姓氏「狐狸」,而我只用名字「梅根」他們有1個朋友,就吐出了這一點:

Megan Fox 
Megan Fox 
Mami Fox 
Mimi Fox 
Mumu Fox 

正如你可以在這裏看到,它吐出「梅根福克斯(我是誰的朋友)「兩次。我認爲這是因爲SQL中的某個地方會吐出所有人,然後吐出朋友。但我怎麼能不吐出每個人,但只有我的朋友?

回答

2

這是因爲運算符的優先級。表達式x and y or z不會評估爲x and (y or z),而是(x and y) or z。因此,朋友限制僅適用於匹配名稱的第一種方式。

您需要周圍的名字條件的一些括號:

WHERE users_friends.bID='$USER' AND users_friends.type = '$typeUsers' AND (
(users.firstname = '$firstname' AND users.lastname='$lastname') OR 
(users.firstname LIKE '$firstname%' AND users.lastname LIKE '$lastname%') OR 
users.firstname LIKE '$firstname%' OR 
users.lastname LIKE '$firstname%' 
) 

至於朋友表連接只適用於一些記錄的條件的一部分,你會從其他用戶也記錄加盟。梅根福克斯出現兩次的原因很可能是因爲她與其他人的朋友,所以她在朋友桌上出現了兩次。

+0

謝謝你的解釋! – Johnson 2010-11-07 16:13:15