使用相同的对象名称按日期获取最新记录

时间:2016-07-25 11:23:41

标签: mysql

我如何获得courseName ='音乐'最新约会?

courseName      |   dateOfEnrollment
----------------|-----------------------
Music           |   2016-07-24
Art             |   2016-07-01
Art             |   2016-07-23  
Music           |   2016-07-25

当我尝试下面的陈述时

SELECT courseName, dateOfEnrollment FROM MyDatabase.dbo.courseEnrollment WHERE courseName = 'Music' AND GETDATE() >= MAX(dateOfEnrollment)

它返回错误:

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

我的最终目标是将该语句放在IF语句中,如果它不为null,那么我将在表中插入新数据。

更新(我的回答):

这对我有用:

IF EXISTS (SELECT TOP 1 courseName, dateOfEnrollment FROM courseEnrollment WHERE courseName = 'Music' ORDER BY dateOfEnrollment DESC)
    *Insert data into the table*

ELSE
    *No need to insert*

2 个答案:

答案 0 :(得分:4)

SELECT
    courseName,
    dateOfEnrollment
FROM
    MyDatabase.dbo.courseEnrollment
WHERE
    courseName = 'Music'
ORDER BY
    dateOfEnrollment
LIMIT 1

您的查询应该如何,但假设您的主要目标 - 您只需要检查是否有任何音乐'你不应该对dateOfEnrollment列感兴趣。我是对的还是错过了什么?

所以你的最终查询(根据条件插入一行)将是:

INSERT INTO courseEnrollment
SELECT 'Music', CURDATE() FROM courseEnrollment
WHERE courseName = 'Music';

答案 1 :(得分:0)

你可以尝试一下:

SELECT 
CE.*
FROM courseEnrollment CE
INNER JOIN 
(
    SELECT 
        courseName,
        MAX(dateOfEnrollment) max_enrollment_date
    FROM courseEnrollment
    WHERE courseName ='Music'
) t
ON CE.courseName = t.courseName AND CE.dateOfEnrollment = t.max_enrollment_date;

注意:如果Music课程下的多个条目具有最新日期,则此查询的输出可能包含多个条目。

<强> TEST:

CREATE TABLE courseEnrollment (
    courseName VARCHAR (100),
    dateOfEnrollment date
);

INSERT INTO courseEnrollment (
    courseName,
    dateOfEnrollment
)
VALUES
    ('Music', '2016-07-24'),
    ('Art', '2016-07-01'),
    ('Art', '2016-07-23'),
    ('Music', '2016-07-25');

对这些给定数据运行上述查询,您将得到如下输出:

<强>输出:

courseName        dateOfEnrollment
Music               2016-07-25

修改

WORKING DEMO