SQL JOIN帮助

时间:2009-01-11 22:58:30

标签: sql join

SELECT * FROM friends WHERE(user1 = $ userid OR user2 = $ userid)AND accepted = 1

如果我想从表“用户”中获取user2的信息,JOIN会是什么样子?

表朋友:   id int(11)NOT NULL auto_increment,   user1 int(11)NOT NULL,   user2 int(11)NOT NULL,   date datetime NOT NULL,   accept tinyint(1)NOT NULL,   type varchar(32)NOT NULL

用户:   id mediumint(8)NOT NULL auto_increment,   username varchar(32)NOT NULL,   password varchar(40)NOT NULL

3 个答案:

答案 0 :(得分:3)

SELECT u.*, f.* FROM friends f 
JOIN users u ON u.id=f.user2 
WHERE (f.user1= $userid OR f.user2=$userid) 
AND f.accepted = 1

答案 1 :(得分:1)

如下所示。

SELECT f.*, u1.*, u2.* FROM friends f
INNER JOIN users u1 ON f.user1 = u1.id
INNER JOIN users u2 ON f.user2 = u2.id
WHERE (f.user1 = $userid OR f.user2 = $userid) AND f.accepted = 1

答案 2 :(得分:1)

你说你没有成功尝试(基于马克泰勒的回答?)

$sql = mysql_query(" SELECT u., f. FROM relations f JOIN users u ON u.id=f.user2 WHERE (f.user1=$row[id] OR f.user2=$userid) AND f.accepted = '1' ");

但不应该

'select u., f. from ...' 

'select u.*, f.* from ...'