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

时间:2013-11-06 09:37:46

标签: mysql sql

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

enter image description here

enter image description here

-- ----------------------------
-- 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

enter image description here

正确的结果应该是:

enter image description here

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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