是否可以将这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;
}
答案 0 :(得分: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 Injection攻击。请改用PDO或预备语句。
答案 1 :(得分: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