2013-10-18 68 views
0

我正在为一个练习项目制作一个基本的通知系统。我有几个表,其中两个看起来像下面这样:while循环中的PHP SQL查询JOIN

> Table 1: "Users" 
> 
userid | username | Firstname | Lastname 
1  | Daffy  | Daffy | Duck 
2  | Flinstone | Fred | Flinstone 
3  | dduck  | Donald | Duck 
> 
> Table 2: "Notifications" 
> 
Notification_id | from_user_id | to_user_id | SeenOrUnseen | type  
    1   | 1   |  2  |  1  | fRequest    
> 2   | 1   |  2  |  0  | comment    
> 3   | 1   |  2  |  1  | comment    
> 4   | 3   |  1  |  1  | fRequest    
> 5   | 2   |  3  |  1  | fRequest    
> 6   | 2   |  3  |  0  | comment    
> 7   | 3   |  2  |  0  | comment 

然后我需要从这两个表中的数据和SQL查询的发送前通常会加入关于USER_ID和from_user_id表。但是,联合似乎会返回多个值,因为在第二个表中有from_user_id的多个实例。相反,我查询数据库,在while循环返回数据,而while循环中发出另一个查询到数据库的不同表的信息:

include('../../db_login.php'); 
$con = mysqli_connect("$host", "$username", "$password", "$db_name"); 
$tbl_name = "Profile"; 
$tplname = "profile_template.php"; 
$tplname2 = "public_profile_template.php"; 
$myid = $_SESSION['identification']; 
//CHECK CONNECTION 
if(mysqli_connect_errno($con)) { 
echo "failed to connect" . mysql_connect_error(); 
}else { 
$result = mysqli_query($con, "SELECT * FROM Notifications WHERE to_user_id='$myid'"); 
$count = mysqli_num_rows($result); 
if($count == 0){ 

    $style = "display:none;"; 
} else { 

echo "<ul class='notifications'>"; 
    while($row = mysqli_fetch_array($result)){ 
    $from_user_id = $row['from_user_id']; 
    $to_user_id = $row['to_user_id']; 
    $seen = $row['seen']; 
    $nature = $row['nature']; 
     $result2 = mysqli_query($con, "SELECT * FROM users WHERE id='$from_user_id'"); 
     $count2 = mysqli_num_rows($result2); 
     if($count2 != 0){ 
     while($row2 = mysqli_fetch_array($result2)){ 
     $fromFirstname = $row2['Firstname']; 
     $fromLastname = $row2['Lastname']; 

     } 
    if($nature == 'fRequest'){ 
    echo "<li> You have received a friend request from" . $fromFirstname . " " . $fromLastname . "</li>"; 
    } 
    } 

    } 
    echo "</ul>"; 
} 


mysqli_close($con); 
} 
       echo "<div id='NoNotification'></div>"; 
       echo "<div id='Notification' style='" . $style . "'></div>"; 
       ?> 

是否有这样做的更好的办法这个?

感谢您的帮助!

+0

是的。重写为联接。你说它不起作用,但这只意味着你没有正确写入连接。像这样的嵌套查询,其中内部查询依赖于来自外部查询的值,是可靠的低效率。 –

+0

是的。有更好的做法。如果您只想要DISTINCT结果,请只选择DISTINCT结果。 – Strawberry

+0

酷,这就是我认为马克B!还有一次加入,但下面的答案几乎是我以前做过的。在这种情况下最好的加入是什么? – Truvia

回答

1

你可以做这样的事情:

SELECT n.*, u.* 
FROM Notifications n 
JOIN users u ON n.from_user_id=u.id 
WHERE n.to_user_id=$myid 
ORDER BY n.id, u.id 

你会得到你需要的所有数据。通知数据和用户数据。最好定义你想要检索的字段而不是*,这样你就可以更好地了解你使用的和不使用的数据。

您正在使用整数(id)作为字符串,您可以将$myid放在那里。此外,请注意,这不是MySQL注入的安全查询。 For more info