1

I have this query that produces a list of foreign keys:

SELECT ad_id 
FROM ads AS i
INNER JOIN ads_earnings AS e
ON i.ad_id = e.earning_ad_id
GROUP BY i.ad_id

I want to use that as the parameter for this query in a loop:

INSERT INTO ads_stats_traffic
(traffic_ad_id,traffic_country_id,traffic_paid,traffic_verified,traffic_total) 
(
    SELECT earning_ad_id, earning_country_id, earning_paid, SUM(earning_verified), COUNT(earning_id)
    FROM ads_earnings
    WHERE earning_ad_id = ?
    GROUP BY earning_paid, earning_country_id
)

How do I do that?

1 Answer 1

1

Using a nested subquery with in should work:

INSERT INTO ads_stats_traffic
(traffic_ad_id,traffic_country_id,traffic_paid,traffic_verified,traffic_total) 
(
    SELECT earning_ad_id, earning_country_id, earning_paid, SUM(earning_verified), COUNT(earning_id)
    FROM ads_earnings
    WHERE earning_ad_id in
    (
        SELECT ad_id 
        FROM ads AS i
        INNER JOIN ads_earnings AS e
        ON i.ad_id = e.earning_ad_id
        GROUP BY i.ad_id
    )
    GROUP BY earning_paid, earning_country_id
)
Sign up to request clarification or add additional context in comments.

1 Comment

Ohhhhh IN.....new SQL word for me......Just going to take my dog walkies and then I try it out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.