目前我有3個表,我想了選擇2臺ID和限制秀達內容如何從2數據庫表中選擇並限制40中的內容?
表名作爲聊天
id | user_id | chat | date
1 1 a 2016-05-29 12:02:58
表名作爲chatroom_chat
chatroom_id | chat_id |
1 1
這裏是我的php代碼與sql語句
$chatroomID=$_GET['chatroomID'];
$userID = $_SESSION['id'];
$sql="SELECT * FROM chatroom_chat WHERE chatroom_id ='$chatroomID'";
$result1 = mysqli_query($connection, $sql) or die(mysqli_error($connection));
while ($row = mysqli_fetch_array($result1)) {
$chat = $row['chat_id'];
$sql3 ="SELECT * FROM (
SELECT * FROM chat,chatroom_chat WHERE id = '$chat' AND chat_id= '$chat' ORDER BY id DESC LIMIT 0,40
) sub
ORDER BY id ASC LMIT 0,40";
$getChatData = mysqli_query($connection,$sql3) or die(mysqli_error($connection));
$getUserID=mysqli_query($connection, "SELECT * FROM chat WHERE id = '$chat'") or die(mysqli_error($connection));
while($getUserIDRow=mysqli_fetch_array($getUserID)){
$postUserID=($getUserIDRow['user_id']);
}
$getUsername=mysqli_query($connection, "SELECT * FROM user WHERE id = '$postUserID'");
while($getUsernameRow=mysqli_fetch_array($getUsername)){
$postUsername=($getUsernameRow['username']);
}
while($row3 = mysqli_fetch_array($getChatData)) {
$color = ($row3['user_id'] == $userID) ? '#FFFFFF' : '#66FFFF';
$position = ($row3['user_id'] == $userID) ? 'right' : 'left';
$border = ($row3['user_id'] == $userID) ? ' 1px solid black ' : ' none ';
echo "<div class='msg-dateandtime' style='text-align:$position; float:$position;'> <div class='left-username' style='color:blue;'>" .$postUsername."</div>"
. "<div class='space'></div>"
. "<div class='right-date'> ". $row3['date'] ." </div></div>"
. "<div class='wrap-message' style='background-color:$color; border:$border; float:$position;'>"
. "<p style 'text-align=$position; margin:0; padding:0; text-align:left;'> ".$row3['chat']."</p></div>";
}
}
now t這裏沒有任何錯誤顯示。只是聊天不會限制在40上。
如果你在'ORDER BY id ASC'旁添加了一個額外的'LIMIT 40',那麼怎麼辦? –
它會有錯誤'你的SQL語法有錯誤;檢查對應於您的MariaDB服務器版本的手冊,在第4行'LMIT 0,40'附近使用正確的語法。 – Chew
確保您爲每個派生表使用別名。例如'chat.id'而不是'id'。它也將增強查詢的可讀性 – sabith