我有一张看起来像这样的表
courseid session_date title published
1 2012-07-01 Training Course A 0
1 2012-07-02 Training Course A 0
2 2012-07-04 Training Course B 1
2 2012-07-07 Training Course B 1
3 2012-07-05 Training Course C 1
3 2012-07-06 Training Course C 1
4 2012-07-07 Training Course D 1
4 2012-07-10 Training Course D 1
该表为每个ID和标题都有两个条目,因为session_date列显示了课程的开始日期和结束日期。
我正在尝试创建一个查询,在过去没有显示任何课程的情况下拉下接下来的五门课程。
我已经走到了这一步
SELECT session_date, title, courseid
FROM table
WHERE published = 1 AND session_date > DATE(NOW())
ORDER BY session_date ASC LIMIT 0,5
这会在接下来的五个会话日期从表中提取行,但它包括开始日期和结束日期,而我需要按开始日期排序的下五个课程。
我需要创建一个查询,它将为每个courseid提取最早的session_date,但忽略具有相同courseid的最新session_date的行,但我完全不知道如何执行此操作。
非常感谢任何帮助或建议。
答案 0 :(得分:2)
如果您按照课程对结果进行分组并选择MAX(session_date)
,您将获得与每门课程相关的最新日期(即完成日期):
SELECT courseid, MIN(session_date) AS start_date
FROM `table`
WHERE published = 1
GROUP BY courseid
HAVING start_date > CURRENT_DATE
ORDER BY start_date ASC
LIMIT 5
在sqlfiddle上查看。
答案 1 :(得分:1)
您需要做的是仅检索每个session_date
组courseid
最少的行,然后按结果集排序:
SELECT
b.*
FROM
(
SELECT courseid, MIN(session_date) AS mindate
FROM tbl
GROUP BY courseid
) a
INNER JOIN
tbl b ON a.courseid = b.courseid AND a.mindate = b.session_date
WHERE
b.session_date > NOW() AND
b.published = 1
ORDER BY
b.session_date
LIMIT 5
但更好的设计是每courseid
只有一行,并且有两列指定开始日期和结束日期:
tbl
------------------
courseid [PK]
start_date
end_date
title
published
然后你就可以做到:
SELECT *
FROM tbl
WHERE start_date > NOW() AND published = 1
ORDER BY start_date
LIMIT 5
答案 2 :(得分:0)
由于SELECT子句中所有列的值都在重复,因此只需使用DISTINCT
SELECT distinct session_date, title, courseid
FROM table
WHERE published = 1 AND session_date > DATE(NOW())
ORDER BY session_date ASC LIMIT 0,5