使我的mysql查询更有效

时间:2013-01-07 14:52:03

标签: mysql database

我要做的是从id表中提取phone_typeos_versionEnswitch_Mobile_Users列。

使用id我只需从enswitch_id表中获取Enswitch_Users

然后计算来自Enswitch_Android_PurchasesEnswitch_Iphone_Purchases的所有内容,其中用户列与enswitch_mobile_users中的ID匹配。获得第一个入学日期和最后一个入学日期。

我设法使其适用于此查询:

SELECT p.user  AS `Mobile_User_ID`, 
    e.os_version `Os_Version`, 
    e.phone_type `Phone_Type`, 
    eu.enswitch_id `Enswitch_ID`,
    Count(1) AS `Buy_Count`,
    (SELECT pc.date 
        FROM 
        (
            SELECT date, user, status 
            FROM enswitch_android_purchases 
            UNION 
            SELECT date, user, status 
            FROM enswitch_iphone_purchases
        ) AS pc 
        WHERE pc.status = 1 
            AND pc.user = p.user 
        ORDER BY pc.date ASC 
        LIMIT 1) AS `First_Purchase`,
    (SELECT pc.date 
        FROM 
        (
            SELECT date, user, status 
            FROM enswitch_android_purchases 
            UNION 
            SELECT date, user, status 
            FROM enswitch_iphone_purchases
        ) AS pc 
        WHERE pc.status = 1 
            AND pc.user = p.user 
        ORDER BY pc.date DESC LIMIT 1) AS `Last_Purchase`
FROM 
(
    SELECT item, date, user, status 
    FROM enswitch_android_purchases 
    UNION
    SELECT item, date, user, status 
    FROM enswitch_iphone_purchases
) AS p 
LEFT JOIN enswitch_mobile_users e 
    ON p.user = e.id
LEFT JOIN enswitch_users eu 
    ON e.user_id = eu.id
WHERE p.`date` >= :from_date 
    AND p.`date` <= :to_date 
    AND p.user is not null 
    AND p.status = 1
GROUP BY `Mobile_User_ID`

但由于选择它会非常慢,所以我怎样才能让它更有效率呢?

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容替换SELECT列表中包含min(p.date)max(p.date)的两个选项:

SELECT p.user  AS `Mobile_User_ID`, 
    e.os_version `Os_Version`, 
    e.phone_type `Phone_Type`, 
    eu.enswitch_id `Enswitch_ID`,
    Count(1) AS `Buy_Count`,
    min(p.date) AS `First_Purchase`,
    max(p.date) AS `Last_Purchase`
FROM 
(
    SELECT item, date, user, status 
    FROM enswitch_android_purchases 
    UNION
    SELECT item, date, user, status 
    FROM enswitch_iphone_purchases
) AS p 
LEFT JOIN enswitch_mobile_users e 
    ON p.user = e.id
LEFT JOIN enswitch_users eu 
    ON e.user_id = eu.id
WHERE p.`date` >= :from_date 
    AND p.`date` <= :to_date 
    AND p.user is not null 
    AND p.status = 1
GROUP BY p.user