我必須顯示兩位候選人之間的會議列表,其中我必須顯示兩位候選人之間最近一次會議的日期和時間以及計數在他們之間安排的所有會議。選擇最近一行並計算一對值的所有條目
查詢我寫來選擇候選人之間的會議:這給
SELECT cm.id AS meeting_id, cm.meeting_date, cm.meeting_time, cm.candidate1_id, cm.candidate2_id
FROM candidate_meetings AS cm
JOIN view_candidate_details AS candidate_1 ON candidate_1.id = cm.candidate1_candidate_id
JOIN view_candidate_details AS candidate_2 ON candidate_2.id = cm.candidate2_candidate_id
WHERE (candidate_1.counselor_member_id = 41 OR candidate_2.counselor_member_id = 41)
ORDER BY cm.id DESC
以下ouptput:
+------------+--------------+--------------+------------------+-----------------+
| meeting_id | meeting_date | meeting_time | candidate1_id | candidate2_id |
+------------+--------------+--------------+------------------+-----------------+
| 6 | 2016-08-31 | 17:45:00 | 24 | 28 |
| 5 | 2016-08-31 | 17:30:00 | 24 | 28 |
| 4 | 2016-08-31 | 19:30:00 | 24 | 23 |
| 3 | 2016-08-31 | 18:30:00 | 24 | 22 |
| 2 | 2016-08-31 | 19:15:00 | 24 | 21 |
| 1 | 2016-08-31 | 17:15:00 | 24 | 21 |
+------------+--------------+--------------+------------------+-----------------+
我們兩個之間的最近一次會議的細節相處計數應聘者,我將此添加到查詢中:
SELECT *, count(*) AS meeting_count
FROM
(
SELECT cm.id AS meeting_id, cm.meeting_date, cm.meeting_time, cm.candidate1_id, cm.candidate2_id
FROM candidate_meetings AS cm
JOIN view_candidate_details AS candidate_1 ON candidate_1.id = cm.candidate1_candidate_id
JOIN view_candidate_details AS candidate_2 ON candidate_2.id = cm.candidate2_candidate_id
WHERE (candidate_1.counselor_member_id = 41 OR candidate_2.counselor_member_id = 41)
ORDER BY cm.id DESC
) as sub
GROUP BY sub.candidate1_id, sub.candidate2_id;
運行此程序後ERY我得到這個結果:
+------------+--------------+--------------+------------------+-----------------+---------------+
| meeting_id | meeting_date | meeting_time | candidate1_id | candidate2_id | meeting_count |
+------------+--------------+--------------+------------------+-----------------+---------------+
| 1 | 2016-08-31 | 17:15:00 | 24 | 21 | 2 |
| 3 | 2016-08-31 | 18:30:00 | 24 | 22 | 1 |
| 4 | 2016-08-31 | 19:30:00 | 24 | 23 | 1 |
| 5 | 2016-08-31 | 17:30:00 | 24 | 28 | 2 |
+------------+--------------+--------------+------------------+-----------------+---------------+
但該預期的結果
+------------+--------------+--------------+------------------+-----------------+---------------+
| meeting_id | meeting_date | meeting_time | candidate1_id | candidate2_id |meeting_count |
+------------+--------------+--------------+------------------+-----------------+---------------+
| 6 | 2016-08-31 | 17:45:00 | 24 | 28 | 2 |
| 4 | 2016-08-31 | 19:30:00 | 24 | 23 | 1 |
| 3 | 2016-08-31 | 18:30:00 | 24 | 22 | 1 |
| 2 | 2016-08-31 | 19:15:00 | 24 | 21 | 2 |
+------------+--------------+--------------+------------------+-----------------+---------------+
PS:請忽略預期的結果id列的順序。
感謝您展示正確的路徑以及爲了給出關於sql標準的知識+1。 – Parth