在一個回應中傳回多個回應資料
在您的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';
在此查詢中:
執行此查詢後,您將獲得包含多個科目記錄的單一回應,每個記錄都包含必要的學生資訊和計算值。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3