1

如何从 c 和 o 表中收集总信息?

在此处输入图像描述

在此处输入图像描述

-- ----------------------------
-- Table structure for `a`
-- ----------------------------
DROP TABLE IF EXISTS `a`;
CREATE TABLE `a` (
  `products_id` int(11) NOT NULL,
  `products_name` varchar(255) default NULL,
  PRIMARY KEY  (`products_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of a
-- ----------------------------
INSERT INTO `a` VALUES ('1', 'hello');
INSERT INTO `a` VALUES ('2', '222');
INSERT INTO `a` VALUES ('3', null);
INSERT INTO `a` VALUES ('4', '');
INSERT INTO `a` VALUES ('5', '5555');
-- ----------------------------
-- Table structure for `c`
-- ----------------------------
DROP TABLE IF EXISTS `c`;
CREATE TABLE `c` (
  `id` int(11) NOT NULL auto_increment,
  `customers_id` int(11) NOT NULL,
  `url` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of c
-- ----------------------------
INSERT INTO `c` VALUES ('1', '1', 'a.html');
INSERT INTO `c` VALUES ('2', '2', 'b.html');
INSERT INTO `c` VALUES ('3', '3', 'c.html');
INSERT INTO `c` VALUES ('4', '1', 'd.html');

我的 sql 代码如下:

select 
    c.customers_id,
    count(c.url) as url_count,
    count(o.orders_id) as count_order,
    sum(o.order_total) as order_totals
from c left join o on c.customers_id = o.customers_id
group by c.customers_id

在此处输入图像描述

正确的结果应该是:

在此处输入图像描述

4

2 回答 2

1

问题在于这c.customers_id不是唯一的,因此您会为客户 1 获得 2*2=4 行。您可以通过首先进行分组来解决这个问题c.customers_id,然后才加入:

SELECT a.customers_id, url_count, order_count, order_totals
FROM    (SELECT   customers_d, COUNT(c.url) AS url_count
         FROM     c
         GROUP BY customers_id) a
JOIN (SELECT   customers_id, 
               COUNT(o.orders_id) AS order_count, 
                SUM(o.order_total) AS order_totals
      FROM     o
      GROUP BY o.customers_id) b ON a.customers_id = b.customers_id              
于 2013-11-06T09:51:37.270 回答
1

像这样试试

select 
    c.customers_id,
    count(o.url) as url_count,
    count(o.orders_id) as count_order,
    sum(o.order_total) as order_totals
from o left join c on c.customers_id = o.customers_id
group by c.customers_id
于 2013-11-06T09:44:28.840 回答