简体   繁体   中英

MySQL get MAX date

I have an Events table and related EventAddress table. I want to get the address of the event that has the latest time on a particular day and less than a given time. So if there are 2 events today, one at 2pm-3pm and one at 5pm-6pm and my next event is at 7pm-8pm, I want to get events with end time earlier than the new event start time. So in the instance, I would want the address of the event that is 5-6pm. Hope that makes sense. The following is what I have so far after trying to follow this SO post .

SELECT
  ea1.Address,
  ea1.City,
  ea1.State,
  ea1.Zip,
  e.EventEndDate
FROM EventAddress ea1
  INNER JOIN (SELECT
      Events.EventAddressId,
      MAX(Events.EventEndDate) AS maxdate
    FROM Events
    GROUP BY Events.EventAddressId) max_record
    ON max_record.EventAddressId = ea1.EventAddressId
  INNER JOIN Events e
    ON ea1.EventAddressId = e.EventAddressId
WHERE DATE(e.EventStartDate) = '2014-11-06'
AND e.FranchiseId = 1
AND TIME(e.EventEndDate) <= '18:00:00'

EDIT: the inner SELECT returns the correct result, but the end result is still returning 2 events.

I think you need to change

WHERE DATE(e.EventStartDate) = '2014-11-06'
AND e.FranchiseId = 1
AND TIME(e.EventEndDate) <= '18:00:00'

To either EventStartDate or EventEndDate. I'm not sure how you're data is structured, but I'm assuming it's something like '2014-11-06 18:00:00'. If so you will need to use the mysql equivalent of datepart.

我在外部选择中添加了MAX(TIME(e.EventEndDate)) AS themax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM