Mysql循环查询结果

时间:2016-02-25 11:36:59

标签: mysql

我有这个查询产生一个外键列表:

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

我想在循环中将其用作此查询的参数:

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
)

我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用带in的嵌套子查询应该有效:

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
)