我有一個網頁,用戶上傳&觀看視頻。上週我asked跟蹤視頻觀看的最佳方式是什麼,以便我可以顯示本週觀看次數最多的視頻(所有日期的視頻)。優化GROUP BY&ORDER BY查詢
現在我需要一些幫助來優化查詢,我從中獲取數據庫中的視頻。相關表是這樣的:
video (~239371 rows)
VID(int), UID(int), title(varchar), status(enum), type(varchar), is_duplicate(enum), is_adult(enum), channel_id(tinyint)
signup (~115440 rows)
UID(int), username(varchar)
videos_views (~359202 rows after 6 days of collecting data, so this table will grow rapidly)
videos_id(int), views_date(date), num_of_views(int)
表video
保存視頻,signup
hodls用戶和videos_views
擁有對影片觀看次數(每個視頻可以在該表中,每天一行)數據。
我有這個疑問,但需要10秒才能執行,我想這隻會隨着videos_views
表的增長而變差。
SELECT
v.VID,
v.title,
v.vkey,
v.duration,
v.addtime,
v.UID,
v.viewnumber,
v.com_num,
v.rate,
v.THB,
s.username,
SUM(vvt.num_of_views) AS tmp_num
FROM
video v
LEFT JOIN videos_views vvt ON v.VID = vvt.videos_id
LEFT JOIN signup s on v.UID = s.UID
WHERE
v.status = 'Converted'
AND v.type = 'public'
AND v.is_duplicate = '0'
AND v.is_adult = '0'
AND v.channel_id <> 10
AND vvt.views_date >= '2001-05-11'
GROUP BY
vvt.videos_id
ORDER BY
tmp_num DESC
LIMIT
8
所有相關字段都被編入索引。 這裏是EXPLAIN結果的屏幕截圖: alt text http://img685.imageshack.us/img685/9440/explain.png
那麼,我該如何優化呢?
UPDATE 這是我基於Quassnoi的答案的查詢。它會返回正確的視頻,但會在註冊表中混淆JOIN。對於某些記錄,username
字段爲NULL,對於其他字段包含錯誤的用戶名。
SELECT
v.VID,
v.title,
v.vkey,
v.duration,
v.addtime,
v.UID,
v.viewnumber,
v.com_num,
v.rate,
v.THB,
s.username
FROM
(SELECT
videos_id,
SUM(num_of_views) AS tmp_num
FROM
videos_views
WHERE
views_date >= '2010-05-13'
GROUP BY
videos_id
) q
JOIN video v ON v.VID = q.videos_id
LEFT JOIN signup s ON s.UID = v.VID
WHERE
v.type = 'public'
AND v.channel_id <> 10
AND v.is_adult = '0'
AND is_duplicate = '0'
ORDER BY
tmp_num DESC
LIMIT
8
下面是結果集: alt text http://img714.imageshack.us/img714/2954/resultu.png
這是不可能的。但嘗試評估Postgres上的數據,檢查它將如何票價 – Hao 2010-05-18 12:49:56
是的,這是不可能的:) – 2010-05-18 14:56:15