基于另一个字段获取一个字段的不同mysql结果

时间:2013-03-20 14:09:16

标签: php mysql distinct

我有这段代码:

select count(distinct affiliate_orders_id) as count
, sum(affiliate_value) as total
, sum(affiliate_payment) as payment 
from " . TABLE_AFFILIATE_SALES . " a 
    left join " . TABLE_ORDERS . " o on (a.affiliate_orders_id = o.orders_id)
where a.affiliate_orders_id = o.orders_id 
and o.orders_status >= " . AFFILIATE_PAYMENT_ORDER_MIN_STATUS . "
        ";

  $affiliate_sales_query= tep_db_query($affiliate_sales_raw);
  $affiliate_sales= tep_db_fetch_array($affiliate_sales_query);

所以,$ affiliate_sales ['total'] = 128000,实际上它应该是32000,因为有多个affiliate_values和affiliate_orders_id。 affilaite_values有些具有相同的值,因此这些值不能区分。 affilaite_orders_id具有所有唯一值,但是有多行,需要区分。然后,affiliate_values必须根据affiliate_orders_id的不同行进行总结,以获得准确的总和。

我正试图获得所有affiliate_values的总和,以及表中有多少个不同的affiliate_orders_id。

1 个答案:

答案 0 :(得分:0)

根据您的更新,我认为这将为您提供所需的信息。您需要使用子查询

SELECT COUNT(a) COUNT, SUM(av) total, SUM(ap) aptotal
FROM (
    SELECT affiliate_orders_id a, affiliate_value av, SUM(affiliate_payment) AS ap
from " . TABLE_AFFILIATE_SALES . " a 
    left join " . TABLE_ORDERS . " o on (a.affiliate_orders_id = o.orders_id
    GROUP BY affiliate_orders_id, affiliate_value)
where a.affiliate_orders_id = o.orders_id 
and o.orders_status >= " . AFFILIATE_PAYMENT_ORDER_MIN_STATUS . ") a

现在这会带来更大的问题。你错过了表中的连接条件吗?通常,您不应该在查询中返回重复日期,因此我建议首先仔细检查您的查询是否正确加入。