1

Web サイトでのユーザーの進行状況を追跡するために使用される、次の一連の MySQL クエリがあります。それらを単純化する良い方法はありますか?

#How many people reached stage 2
SELECT COUNT(DISTINCT a.session_id) as "total"
    FROM formation_page_hits a
    WHERE a.progress = 2
    AND DATE(a.datetime) = "2011-03-23";

#How many people reached stage 4 having reached stage 2
SELECT COUNT(DISTINCT a.session_id) as "total"
    FROM formation_page_hits a, (SELECT f.session_id, f.`datetime`
                        FROM formation_page_hits f
                        WHERE f.progress = 2) as b
    WHERE a.progress = 4
    AND a.session_id = b.session_id
    AND DATE(b.datetime) = "2011-03-23"
    AND DATE(a.datetime) = "2011-03-23";


#How many people reached stage 7, having reached stage 4, having reached stage 2
SELECT COUNT(DISTINCT a.session_id) as "total"
    FROM formation_page_hits a, (SELECT f.session_id, f.`datetime`
                        FROM formation_page_hits f
                        WHERE f.progress = 4) as b, (SELECT f.session_id, f.`datetime`
                        FROM formation_page_hits f
                        WHERE f.progress = 2) as c
    WHERE a.progress = 7
    AND a.session_id = b.session_id
    AND a.session_id = c.session_id
    AND DATE(c.datetime) = "2011-03-23"
    AND DATE(b.datetime) = "2011-03-23"
    AND DATE(a.datetime) = "2011-03-23";

ご覧のとおり、同じ情報を非常に迅速に再クエリしており、同じパターンに従う追加の 4 つまたは 5 つのクエリがあります。 「ステージ 2 に到達した人数」は?

編集:各ページ ビューは、formation_page_hits のエントリとして保存されるため、各セッションのページ ビューの完全な記録が存在します。

id_formation_page_hits INT PRIMARY_KEY, session_id VARCHAR(100), datetime DATETIME, progress INT
4

1 に答える 1

1
SELECT  COUNT(*)
FROM    (
        SELECT  session_id
        FROM    formation_page_hits
        WHERE   progress IN (2, 4, 7)
                AND datetime >= '2011-03-23'
                AND datetime < '2011-03-24'
        GROUP BY
                session_id
        HAVING  COUNT(DISTINCT progress) = 3
        ) q

これを高速に動作させるには、複合インデックスを作成します(session_id, datetime, progress)

于 2011-03-28T16:04:35.573 に答える