2

我有一张看起来像这样的桌子

    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 和 Title 都有两个条目,因为 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 的行,但我完全不知道如何执行此操作。

任何帮助或建议将不胜感激。

4

3 回答 3

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上查看。

于 2012-07-04T22:38:04.107 回答
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
于 2012-07-04T22:47:09.637 回答
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

于 2012-07-04T22:50:57.543 回答