0

我有 2 个具有以下结构的表:

CREATE TABLE IF NOT EXISTS `campaigns` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

CREATE TABLE IF NOT EXISTS `campaign_stats` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_campaign` int(11) NOT NULL,
  `day` int(11) NOT NULL,
  `cost` varchar(255) NOT NULL,
  `conv` int(11) NOT NULL,
  `cost_conv` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1457 ;

现在costandcost_conv字段是美元值,例如12.13or 143.00

day字段包含存储为 INT 的 unix 时间戳。

我要做的是获取昨天的 、 和字段的总和costconv并将cost_conv它们输出到 HTML 表中。

这是我的代码:

<h2>Yesterday</h2>

<?php

$sql = mysql_query("
                    select c.name,
                    (select sum(conv) from campaign_stats where id_campaign=c.id and day=date(from_unixtime(day) - interval 1 day)) as num_conv,
                    (select sum(cast(cost as float)) from campaign_stats where id_campaign=c.id and day=date(from_unixtime(day) - interval 1 day)) as num_cost,
                    (select sum(cast(cost_conv as float)) from campaign_stats where id_campaign=c.id and day=date(from_unixtime(day) - interval 1 day)) as num_cost_conv
                    from campaigns as c
                    order by c.name
                    ") or die(mysql_error());

if (mysql_num_rows($sql) == 0)
{
    echo '<p>No campaign information to display.</p>';
}
else
{
    echo '<table cellpadding="10" cellspacing="1" border="0" width="100%">';
    echo '<tr>';
    echo '<th>Account</th>';
    echo '<th>Conversions</th>';
    echo '<th>Cost</th>';
    echo '<th>Cost per Conversion</th>';
    echo '</tr>';

    while ($row = mysql_fetch_assoc($sql))
    {
        foreach ($row as $k => $v)
            $$k = htmlspecialchars($v, ENT_QUOTES);

        echo '<tr class="'.(($count % 2) ? 'row1' : 'row2' ).'">';
        echo '<td>'.$name.'</td>';
        echo '<td>'.$num_conv.'</td>';
        echo '<td>'.$num_cost.'</td>';
        echo '<td>'.$num_cost_conv.'</td>';
        echo '</tr>';

        $count++;
    }

    echo '</table>';
}

?>

它给了我以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'float)) from campaign_stats where id_campaign=c.id and day=date(from_unixtime(da' at line 2

老实说,我什至不确定我是否正确编写了查询。任何帮助将不胜感激。

4

1 回答 1

1

首先,我不喜欢您的查询的编写方式,您可以用单个联接替换子查询。您的查询可能是这样的:

select
  campaigns.name,
  sum(campaign_stats.conv) as num_conv,
  sum(cast(campaign_stats.cost as float)) as num_cost,
  sum(cast(campaign_stats.cost_conv as float)) as num_cost_conv
from
  campaigns inner join campaign_stats on campaigns.id=campaign_stats.id_campaign
where
  date(campaign_stats.day) = date_sub(date(now()),interval 1 day)
group by
  campaigns.name
order by
  campaigns.name
于 2012-10-29T09:31:20.083 回答