2013-05-01 163 views
1

表聯賽子查詢或加入MySQL?

team_id name  wins losses played recorded created 
1  dodgers  10  4  14  1364790000 1353215830 
2  angels  9  6  15  1364790000 1353661376 
3  pirates  12  3  15  1364790000 1353543466 

team_id name  wins losses played recorded created 
1  dodgers  22  9  31  1367274480 1353215830 
2  angels  14  17  31  1367274480 1353661376 
3  pirates  19  13  32  1367274480 1353543466 
4  yankees  10  9  19  1367274480 1365577298 
5  brewers  7  11  18  1367274480 1365394448 

想結果爲:

team_id name  wins losses played 
1  dodgers  12  5  17  
2  angels  5  11  16 
3  pirates  7  10  17 
4  yankees  10  9  19 
5  brewers  7  11  18 

我試過幾個查詢連接並沒有成功。每一天,球隊都會獲得勝利,失敗並參加比賽,並在錄製的專欄上記錄時間標記。該團隊創建在創建的列上。 (所有unix時間戳)我想要的2個日期之間有幾行,但我不需要它們進行此查詢。

我想要做的是讓四月的韓元/丟失/效力於現有的和新的球隊,我試了幾個疑問,這裏有一對夫婦沒有給我想要的結果:

SELECT a.name as name, a.wins-b.wins as wins, a.losses-b.losses as losses, a.played-b.played as played from league a join league b on a.id=b.id where a.recorded= 1367274480 and b.recorded= 1364790000 

SELECT new.*, new.wins-old.wins as newwins, new.losses-old.losses as newlosses FROM league new LEFT JOIN league old ON new.id=old.id WHERE (new.recorded=1367274480 and old.recorded=1364790000) or (new.created > 1364790000 and new.recorded=1367274480) GROUP BY new.id 
+0

什麼數據類型用於'錄製'和'創建'列?他們是否應該是某種日期時間表示? – 2013-05-01 01:50:14

+0

它們是存儲爲int的日期的unix_timestamp()版本。 – piotrm 2013-05-01 02:30:38

+0

我知道,我希望「時間戳」是** NOT **日期時間值,但是是支持樂觀鎖定的引用計數器。它不能用於可靠地重新生成日期時間。 – 2013-05-01 02:36:34

回答

0

你想每一行,爲後來的記錄,並在早些時候相同的行數,所以你需要使用LEFT JOIN來獲取NULL的兩個日期之間創建的團隊,但WHERE recorded較小表的條件應該作爲ON條件進行移動。

另外請記住,2-NULL = NULL,所以你需要用coalesce()將NULL改成0。

SELECT a.name AS name, 
     a.wins - COALESCE(b.wins, 0) AS wins, 
     a.losses - COALESCE(b.losses, 0) AS losses, 
     a.played - COALESCE(b.played, 0) AS played 
FROM league a LEFT JOIN league b 
ON a.team_id = b.team_id AND b.recorded =1364790000 
WHERE a.recorded =1367274480 
+0

謝謝!這很好用。我在左外野,我非常感謝你回答我的問題。 – RobertRinCA 2013-05-01 02:37:27

0

數據設置的方式,似乎你沒有每天的記錄值。但是,每一列都會增加,因此您可以將該月份的最大值和最小值之間的差值計算出來。

試試這個:

SELECT l.name as name, 
     max(l.wins)-min(l.wins) as wins, 
     max(l.losses)-min(l.losses) as losses, 
     max(l.played)-min(l.played) as played 
from league l 
where l.recorded <= 1367274480 and l.recorded >= 1364790000 
group by l.name 
+0

適用於4月份之前創建和參賽的球隊,但不適用於4月份開始參賽的球隊。日期範圍也翻轉了你的答案。我感謝你的時間! – RobertRinCA 2013-05-01 02:56:30