0

是否可以将这 3 个查询放在一个 sql 查询中?

我已经研究过 JOIN,但无法弄清楚如何计算展示次数和点击次数 - 见下文

$date_where = "   rec_use_date > '2013-04-16 17:05:00' AND rec_use_date < '2013-04-23 00:00:00'  ";

    $q = " SELECT * FROM tracking_table ";
    $q .= " WHERE ".$date_where;



    $o =0;
    $result = mysql_query($q); 
    while ($db = mysql_fetch_assoc($result)) {

        $rowKey = md5($db['rec_trk_id']);


        $rows[$rowKey]['use_ip'] = $db['rec_use_ip'];
        $rows[$rowKey]['ad_code'] = $db['rec_trk_id'];
        $rows[$rowKey]['ad_location'] = $db['rec_tar_page'];


        $q_impressions = mysql_query("SELECT COUNT(*) FROM tracking_table WHERE rec_trk_id = '{$db['rec_trk_id']}' AND rec_use_ip LIKE 'Ad loaded' AND ".$date_where) or die(mysql_error());
        $db_impressions = mysql_fetch_assoc($q_impressions);
        $rows[$rowKey]['impressions'] = $db_impressions['COUNT(*)'];
        ++$o;


        $q_clicks = mysql_query("SELECT COUNT(*) FROM tracking_table WHERE rec_trk_id = '{$db['rec_trk_id']}' AND rec_use_ip NOT LIKE 'Ad loaded' AND ".$date_where) or die(mysql_error());
        $db_clicks = mysql_fetch_assoc($q_clicks);
        $rows[$rowKey]['clicks'] = $db_clicks['COUNT(*)'];



        $rows[$rowKey]['conversion'] = round((($db_clicks['COUNT(*)']/$db_impressions['COUNT(*)'])*100),2);

        ++$o;
    }
4

2 回答 2

1

你可以这样做:

SELECT 
  SUM(CASE WHEN rec_use_ip LIKE     'Ad loaded' THEN 1 ELSE 0 END) AS LoadedCounts,
  SUM(CASE WHEN rec_use_ip NOT LIKE 'Ad loaded' THEN 1 ELSE 0 END) AS NotLoadedCounts
FROM tracking_table 
WHERE rec_trk_id = '{$db['rec_trk_id']}' AND ".$date_where

请注意:请停止使用mysql_*扩展,它们已被弃用,并且您的代码这样容易受到SQL 注入的攻击。请改用PDO或准备好的语句。

于 2013-04-22T07:25:34.820 回答
0

你可以使用这样的子查询

SELECT
    tt.*,
    tt1.c AS count_1
FROM tracking_table tt
LEFT OUTER JOIN (
    SELECT
        rec_trk_id,
        COUNT(*) AS c
    FROM tracking_table
    WHERE rec_use_ip LIKE 'Ad loaded'
        AND rec_use_date > '2013-04-16 17:05:00'
        AND rec_use_date < '2013-04-23 00:00:00'
    GROUP BY rec_trk_id
) AS tt1
    ON tt1.rec_trk_id = tt.rec_trk_id
于 2013-04-22T07:27:49.077 回答