在一個回應中傳回多個回應資料
在您的PHP 程式碼中,您有一個從資料庫表中取得多行資料的查詢。但是,您收到多個回應,並且希望將它們合併為具有多個記錄的單一回應。
要實現此目的,您需要修改查詢以對必要的表執行左聯接。您將獲取主題數據並使用左連接包含相關學生信息,而不是獲取學生數據。這將允許您在單一回應中包含多個表中的相關資料。
以下是更新後的查詢示例:
<code class="php">$sql = 'SELECT subjects.userid, users.name AS username, ( SELECT id FROM tbsubjects WHERE userid = subjects.userid ORDER BY id ASC LIMIT 1 ) AS subjectsid, ( SELECT name FROM tbsubjects WHERE userid = subjects.userid ORDER BY time DESC LIMIT 1 ) AS subjectname, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND month = DATE_FORMAT(NOW(), "%c") ) AS activepts, IFNULL(SUM(subjects.points), 0) AS totalpts, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND semester = 1 ) AS sem1, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND semester = 2 ) AS sem2, ( SELECT IFNULL(SUM(points), 0) FROM tbsubjects WHERE userid = subjects.userid AND semester = 3 ) AS sem3 FROM tbsubjects AS subjects LEFT JOIN tbusers AS users ON users.id = subjects.userid WHERE subjects.userid = :userid GROUP BY subjects.userid ORDER BY subjects.time DESC';</code>
在此查詢中:
執行此查詢後,您將獲得包含多個主題記錄的單一回應,每個都有必要的學生資訊和計算值。
以上是如何在單一 MySQL 查詢中取得多筆記錄及其相關資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!