我有3张桌子:
用户
id
username
图像
id
user_id
image
user_follow
id
user_id
follow_id
我尝试进行查询,以显示我朋友的所有朋友和朋友。 我需要通过他们的id(来自表“users”)获取他们的用户名
我的查询是:
$sql = "SELECT f.user_id, username, i.image, i.date FROM users u
INNER JOIN user_follow f on (u.id = f.follow_id)
LEFT OUTER JOIN images i on (f.follow_id = i.user_id)
WHERE
f.user_id = 3 OR f.user_id IN
(
select f2.follow_id
from user_follow f2
where f2.user_id = 3
)
";
并且这个:
[0] => Array
(
[user_id] => 6
[username] => 7777
[image] =>
[date] =>
)
[1] => Array
(
[user_id] => 6
[username] => 8888
[image] => 86o99fyyocscfvbzlco0_380.jpg
[date] => 2012-01-23 15:03:26
)
[2] => Array
(
[user_id] => 3
[username] => 6666
[image] => my.jpg
[date] => 2012-01-23 16:40:28
)
[user_id] => 6 =“用户”表中的名称是6666 [user_id] => 7 =“用户”表中的名称是7777
此查询显示除user_id名称之外的所有内容。我需要对查询进行更改,它还会显示user_id(来自“user_follow”表) - >用户名(在“用户表”中)
答案 0 :(得分:1)
使用join
添加users
user_id
,并在匹配的行中显示username
?
<强>更新强>
SELECT f.user_id, fn.username, i.image, i.date
FROM
users u
INNER JOIN user_follow f on (u.id = f.follow_id)
LEFT OUTER JOIN images i on (f.follow_id = i.user_id)
JOIN users AS fn ON (f.user_id=fn.id)
WHERE
f.user_id = 3 OR f.user_id IN
(
select f2.follow_id
from user_follow f2
where f2.user_id = 3
)