-1

次の 3 つの SQL クエリがあります。

最初のクエリ:

SELECT DISTINCT     company.company_name AS CompanyName, pts AS CompanyPts
FROM                users_pts, users_codes, company
WHERE               scanned = 1 
AND                 users_codes.company_id = company.company_id 
AND                 users_codes.company_id = users_pts.company_id 
AND                 users_codes.email = 'test@gmail.com'
GROUP BY            company.company_id

2 番目のクエリ:

SELECT SUM(IF(completed = 0, 1, 0)) AS NumberOfSurveys 
FROM users_survey_answers
WHERE users_survey_answers.email = 'test@gmail.com'
GROUP BY users_survey_answers.company_id

3 番目のクエリ:

SELECT SUM(IF(redeemed = 0, 1, 0)) AS NumberOfRewards
FROM users_rewards
WHERE users_rewards.email = 'test@gmail.com'
GROUP BY users_rewards.company_id

電子メールの列はすべてのデータベースにあるので、どこから入手したか心配する必要はありません。(users_rewards.email か users_survey_answers.email かは関係ありません)

始めるのに助けが必要です。

みんなありがとう

4

1 に答える 1

2

サブクエリで実行できます

select distinct
    c.company_name as CompanyName, pts as CompanyPts,
    (
        select sum(if(usa.completed = 0, 1, 0))
        from users_survey_answers as usa
        where
            usa.email = uc.email and
            usa.company_id = uc.company_id
    ) as NumberOfSurveys,
    (
        select sum(if(ur.completed = 0, 1, 0))
        from users_rewards as ur
        where
            ur.email = uc.email and
            ur.company_id = uc.company_id
    ) as NumberOfRewards
from users_pts as upusers_codes as uc, company as c
where
    scanned = 1 and
    uc.company_id = c.company_id and
    uc.company_id = up.company_id and
    uc.email = 'test@gmail.com'

結合でそれを行うことも可能です

select distinct
    c.company_name as CompanyName, pts as CompanyPts,
    ifnull(usa.NumberOfSurveys, 0) as NumberOfSurveys,
    ifnull(ur.NumberOfRewards, 0) as NumberOfRewards
from company as c
    inner join users_codes as uc on uc.company_id = c.company_id
    inner join users_pts as up on up.company_id = c.company_id
    left outer join
    (
        select
            t.email, t.company_id,
            sum(if(t.completed = 0, 1, 0)) as NumberOfSurveys 
        from users_survey_answers as t
        group by t.email, t.company_id
    ) as usa on usa.email = uc.email and usa.company_id = uc.company_id
    left outer join
    (
        select
            t.email, t.company_id,
            sum(if(t.redeemed = 0, 1, 0)) as NumberOfRewards
        from users_rewards as t
        group by t.email, t.company_id
    ) as ur on ur.email = uc.email and ur.company_id = uc.company_id
where
    scanned = 1 and
    uc.email = 'test@gmail.com'
于 2012-12-01T07:34:40.280 に答える