2013-04-24 72 views
1

我有两个表,我想比较并找到用户名不符合的用户,然后显示未被跟踪的用户的用户名。SQL从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),然后得到所有的用户名的用户($用户名)的列表不继(表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>"; 
} 
} 
} 
+0

您是否听说过['LEFT JOIN'](http://google.com/?q=LEFT+JOIN)或['JOIN'](http://google.com/?q=SQL+JOIN )本身? – shadyyx 2013-04-24 15:56:57

+0

我没有。这将如何帮助? – derekshull 2013-04-24 15:59:06

+0

请参阅http://dev.mysql.com/doc/refman/5.0/en/join.html,了解如何在MySQL中使用它,以及我如何在这种情况下使用它的例子。 。 (你在使用MySQL吗?) – 2013-04-24 16:02:41

回答

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

+0

检查我刚刚添加的编辑,我认为它会给出更多的清晰度,我插入你的代码,它不起作用 – derekshull 2013-04-24 16:11:33

+0

我接受回到上面......有些东西在工作,但它没有显示用户名,你能看一看,看看为什么可能是这样吗?我把它放在原始文章中 – derekshull 2013-04-24 16:13:39

+0

@derekshull:更新 - 我的早期版本包括一堆列 – 2013-04-24 16:15:00