2

嗨,我有两张这样的桌子-

Event
id   title
1    'Test 1'
2    'Test 2'
3    'Test 3'

and Schedule
id  event_id   price   event_date
1      1         100    2013-04-15
2      1         150    2013-04-20
3      2         80     2013-04-18
4      3         120    2013-04-26
5      3         140    2013-04-22
6      2         100    2013-04-22

我想要以下事件 - 由 event_date ASC 排序的唯一事件

e.id   e.title   s.price   s.event_date
1       Test 1    100       2013-04-15
2       Test 2    80        2013-04-18
3       Test 3    140       2013-04-22

我试过这样查询 -

SELECT e.id, 
       e.title, 
       s.price, 
       Min(s.event_date) AS min_start 
FROM   events AS e 
       JOIN schedules AS s 
         ON ( e.id = s.event_id ) 
GROUP  BY s.event_id; 

然后通过迭代先前查询的结果集再次查询事件。但这是太多的查询。我也没有得到正确的价格。实现上述结果的最佳方法是什么?谢谢

4

5 回答 5

2

可以有许多可能的解决方案来解决您的问题。我曾经这样做的一个方法是使用一个单独的子查询,它event_date为每个event_ID. 然后将结果连接回另一个表以获取其他列。

SELECT  a.ID, a.Title,
        b.Price, b.Event_date
FROM    `Event` a
        INNER JOIN `Schedule` b
            ON a.ID = b.event_ID
        INNER JOIN
        (
            SELECT  event_ID, MIN(event_date) min_date
            FROM    `Schedule`
            GROUP   BY event_ID
        ) c ON b.event_ID = c.event_ID AND
                b.event_date = c.min_date

输出

╔════╦════════╦═══════╦══════════════════════════════╗
║ ID ║ TITLE  ║ PRICE ║          EVENT_DATE          ║
╠════╬════════╬═══════╬══════════════════════════════╣
║  1 ║ Test 1 ║   100 ║ April, 15 2013 00:00:00+0000 ║
║  2 ║ Test 2 ║    80 ║ April, 18 2013 00:00:00+0000 ║
║  3 ║ Test 3 ║   140 ║ April, 22 2013 00:00:00+0000 ║
╚════╩════════╩═══════╩══════════════════════════════╝

如果您只对这两列感兴趣,最简单的方法是

于 2013-04-15T15:03:40.027 回答
0
SELECT   s.title, a.event_id, a.price, a.event_date
  FROM schedule a JOIN event s ON a.event_id = s.ID
 WHERE a.event_date = (SELECT MIN (b.event_date)
                         FROM schedule  as b
                        WHERE b.event_id = a.event_id)
 ORDER BY a.event_id ASC
于 2013-05-15T10:16:05.070 回答
0

您可以创建一个视图并从中选择:

CREATE VIEW scheduleview AS select * from schedule group by event_date,event_id;
select * from scheduleview group by event_id;
于 2013-12-10T10:11:36.493 回答
0

它看起来很复杂,但也更简单

select * from 

    (select 
           event.id,
           event.title,
           schedule.event_date,
           schedule.price,
           event_id 
    from schedule 
    left join event on event.id=schedule.event_id 
    group by event_date,event_id
    )s

group by s.event_id;
于 2013-12-11T06:05:35.643 回答
0

select a.id, a.title, b.price, b.event_date from eventa inner join scheduleb ON a.id = b.event_id order by b.event_id desc ;

于 2014-09-24T05:18:05.730 回答