sql join查询问题

时间:2012-08-05 11:16:49

标签: sql join

我正在制作一个朋友列表,其中包括2个表,FRIENDS表和PLAYERS表。

朋友表

 player   target     status
 -----------------------------
 john     eric       invited
 roger    moore      friends
 stan     winston    friends

球员表

 name      pic     
 -------------------
 john     lol.jpg
 stan     skinhead.gif

现在,在玩家页面上,我需要遍历friends表,找出他们有多少朋友。所以为此,我必须同时检查player字段和{$ 1}}字段= $ name

然后获取pic id必须使用target表加入。

这是我到目前为止的查询,它显然不起作用(psuedo的位):

players

$ name是您所在的球员档案的名称。

任何人都可以告诉我如何调整它以使其有效吗?

3 个答案:

答案 0 :(得分:1)

SELECT p.pic, p.name FROM friends f INNER JOIN players p ON f.name=p.name WHERE (f.player='" .$name. "' OR f.target='" .$name. "') AND status='friends

朋友= f.player 在您的查询?

答案 1 :(得分:1)

您需要使用联合在一个查询中获取所有内容。

SELECT * FROM friends JOIN players ON (target = name AND status = friends)
WHERE player = ?
UNION ALL
SELECT * FROM friends JOIN players ON (player = name AND status = friends)
WHERE target = ?

答案 2 :(得分:1)

试试这个:

SELECT p.pic, 
       p.name 
FROM friends f 
   INNER JOIN players p ON p.name IN (f.player, f.target)
WHERE (f.player='" .$name. "' OR f.target='" .$name. "') 
AND status='friends'

的简写
SELECT p.pic, 
       p.name 
FROM friends f 
   INNER JOIN players p ON p.name = f.player OR p.name = f.target
WHERE (f.player='" .$name. "' OR f.target='" .$name. "') 
AND status='friends'