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>";
?>
是否有這樣做的更好的辦法這個?
感謝您的幫助!
是的。重寫爲聯接。你說它不起作用,但這隻意味着你沒有正確寫入連接。像這樣的嵌套查詢,其中內部查詢依賴於來自外部查詢的值,是可靠的低效率。 –
是的。有更好的做法。如果您只想要DISTINCT結果,請只選擇DISTINCT結果。 – Strawberry
酷,這就是我認爲馬克B!還有一次加入,但下面的答案几乎是我以前做過的。在這種情況下最好的加入是什麼? – Truvia