2013-04-15 217 views
2

你好我有兩個表這樣的 -Mysql的複雜查詢

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; 

然後通過迭代先前查詢的結果集再次查詢事件。但這是太多的查詢。我也沒有得到正確的價格。達到以上結果的最佳方式是什麼?謝謝

回答

2

可以有許多可能的解決方案來解決您的問題。其中之一,我曾經這樣做是通過使用一個單獨的子查詢,每event_ID獲得第一個event_date。然後將結果連接到另一個表以獲取其他列。

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 ║ 
╚════╩════════╩═══════╩══════════════════════════════╝ 

的simpliest方式,如果你只在兩列感興趣的是

+0

謝謝,這是我一直在尋找,但有沒有subquerying方式? – Shwetanka

+0

使用相關的子查詢,但仍然是子查詢。 ':D'我寧願這樣做,因爲mysql不支持窗口函數。 –

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 
0

,你可以創建一個視圖並從中選擇:

CREATE VIEW scheduleview AS select * from schedule group by event_date,event_id; 
select * from scheduleview group by event_id; 
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; 
0

選擇a.id,a.title, b.price,從event b.event_date 一個 內連接schedule b ON a.id = b.event_id order by b.event_id desc;