2013-04-24 52 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