SQL从2个表中获取信息并进行比较

时间:2013-04-24 15:53:57

标签: php sql compare

我想要比较2个表,找到用户名没有关注的用户,然后显示未被跟踪的用户名。

Edit:
Table 1: users 
username

Table 2: follow
username (the name of the user)
followname (the name of the person the user follows)

In Table 2 username and followname are never null.  When a user follows another user then it is put into the list like so:

Username          Followname
derekshull         dvdowns
derekshull         testuser
dvdowns            testuser
testuser           1511project
derekshull         newuser

在我的脑海中,我看到表1获取了所有用户名的列表(列名是表1中的“用户名”),然后获取用户($ username)未跟随的所有用户名列表(列名是表2中的“followname”。

如何比较两个列表而不显示用户已经关注的用户名?

这就是我现在所拥有的。出于某种原因,它显示我关注的用户,但没有关注。

$alluserslookup = mysql_query("SELECT * FROM users WHERE username!='$username'");
$thefollowerslookup = mysql_query("SELECT * FROM follow WHERE username='$username'");

while ($followersrow = mysql_fetch_assoc($thefollowerslookup)) {
$afollower = $followersrow['followname'];

while ($allusersrow = mysql_fetch_assoc($alluserslookup)) {
$allusers = $allusersrow['username'];

if ($afollower != $allusers) {
echo "<a href='viewprofile.php?viewusername=$allusers'>$allusers</a><br>";
}
}
}

1 个答案:

答案 0 :(得分:1)

(更新)尝试:

select u.* from users u
left join follow f on u.username = f.followname and f.username = 'derekshull'
where f.followname is null

SQLFiddle here