Mysql复杂查询

时间:2013-04-15 15:01:43

标签: mysql sql

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

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; 

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

5 个答案:

答案 0 :(得分: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 ║
╚════╩════════╩═══════╩══════════════════════════════╝

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

答案 1 :(得分: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

答案 2 :(得分:0)

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

CREATE VIEW scheduleview AS select * from schedule group by event_date,event_id;
select * from scheduleview group by event_id;

答案 3 :(得分: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;

答案 4 :(得分:0)

选择a.id,a.title,         b.price,b.event_date 来自event a         内连接schedule b             ON a.id = b.event_id 按b.event_id描述;