我有兩個表(MySQL,InnoDB),它們相互之間持有一些分數信息。我想從這兩個方面創建一個排行榜。 與Table-2相比,Table-1的得分更高(^ 2)。MySQL聯合或創建一箇中間表?
一個策略是兩個使用UNION語句編寫SQL查詢並動態獲取結果,另一個策略是創建另一個表並將數據從兩個表中及時插入。 (例如Cron-Job)
我的問題是這個UNION查詢會是多麼昂貴?
SELECT
username,
specialId,
SUM(correct) points,
IFNULL((SUM(foracc)/SUM(completegames)), 0) accuracy
FROM
((SELECT
u.username,
u.specialId,
POW(p.correct, 2) as correct,
p.correct as foracc, #to calcuate accuracy
p.completegames
FROM
Table_01 p
LEFT JOIN users u ON u.userid = p.userid
WHERE
p.year = 2012 AND p.type = 1) UNION (SELECT
u.username,
u.specialId,
p.correct,
p.correct as foracc, #to calcuate accuracy
p.completegames
FROM
Table_02 p
LEFT JOIN users u ON u.userid = p.userid
WHERE
p.year = 2012 AND p.type = 1)) AS Table_aggregatedscore
GROUP BY 1
ORDER BY points DESC , acc DESC
LIMIT 10;
Table_01和Table_02都有超過2000萬行。
PS。我沒有時間/能力來衡量這兩件事情。