我的SQL唯一值 - 意外结果

时间:2013-12-19 12:15:36

标签: mysql sql select group-by sql-order-by

我有一个表tblSchedule,以下是其中的值。

INSERT INTO tblSchedule (`scheduleID`, `eventID`, `price`, `eventDate`) VALUES 
(1, 1, 150, '2013-04-20 00:00:00'),
(2, 1, 100, '2013-04-15 00:00:00'),
(3, 2, 80, '2013-04-18 00:00:00'),
(4, 3, 120, '2013-04-26 00:00:00'), 
(5, 3, 140, '2013-04-22 00:00:00'),
(6, 2, 100, '2013-04-22 00:00:00');

我想获得eventDate ASC订购的Unique事件。
我尝试过以下查询,但这会给出错误的价格值和正确的eventDates。

SELECT MIN(eventDate) as minEventDate, eventId, price
FROM tblSchedule
GROUP BY eventID
ORDER BY minEventDate

Click Here to see code in action

有人能告诉我这里发生了什么以及正确查询的细分吗?

3 个答案:

答案 0 :(得分:3)

首先,您应该为每个MIN(EventDate)找到eventID,然后使用JOIN

找到包含这些eventIDMIN(EventDate)的原始表格中的行
SELECT * FROM tblSchedule
JOIN
 ( SELECT MIN(eventDate) as minEventDate, 
          eventId
        FROM tblSchedule
   GROUP BY eventID
 ) as T on tblSchedule.eventID=t.EventId
           AND
           tblSchedule.eventDate=t.minEventDate

ORDER BY eventDate  

SQLFiddle demo

答案 1 :(得分:1)

试试这个:

SELECT eventDate, eventId, price 
FROM (SELECT eventDate, eventId, price
      FROM tblSchedule
      ORDER BY eventId, eventDate
     ) AS A 
GROUP BY eventId;

检查SQL FIDDLE DEMO

<强>输出

|                    EVENTDATE | EVENTID | PRICE |
|------------------------------|---------|-------|
| April, 15 2013 00:00:00+0000 |       1 |   100 |
| April, 18 2013 00:00:00+0000 |       2 |    80 |
| April, 22 2013 00:00:00+0000 |       3 |   140 |

答案 2 :(得分:0)

您可以为此

使用时间戳
SELECT * FROM `tblschedule` ORDER BY TIMESTAMP( eventDate )

OR

SELECT DISTINCT(eventID) as event, eventDate FROM `tblschedule` ORDER BY TIMESTAMP( eventDate )

而不是*你可以放置你想要返回的任何列。

SQL FIDDLE DEMO