如何获取分组行的计数

时间:2014-07-11 13:12:28

标签: mysql sql group-by having

我需要经销商ID,它有多家汽车供应商。 通过示例表,我需要获得id 3。 我坚持这个问题:

SELECT COUNT(car.id), dealers2cars.dealer_id, car.vendor_id FROM car, dealers2cars
WHERE 
dealers2cars.`car_id` = car.id
GROUP BY car.vendor_id, dealers2cars.`dealer_id`

但结果不对(所有经销商和他们的汽车数量按供应商分组)。

count dealer_id vendor_id
2,1,1 
1,3,1 
3,2,2 
1,3,2

这是示例数据库表:

CREATE TABLE `car` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
  `vendor_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*Data for the table `car` */

insert  into `car`(`id`,`title`,`vendor_id`) values 
(1,'F1',1),
(2,'480 Italia',1),
(3,'New Beatle',2),
(4,'Scirocco',2),
(5,'Golf',2);

/*Table structure for table `dealers2cars` */

CREATE TABLE `dealers2cars` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dealer_id` int(11) DEFAULT NULL,
  `car_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

/*Data for the table `dealers2cars` */

insert  into `dealers2cars`(`id`,`dealer_id`,`car_id`) values 
(1,1,1),
(2,1,2),
(3,2,3),
(4,2,4),
(5,2,5),
(6,3,1),
(7,3,5);

2 个答案:

答案 0 :(得分:1)

我相信,你需要一个内部联接(而不是你使用的交叉联接)

SELECT 
    COUNT(car.id) as carCount, 
    dealers2cars.dealer_id, 
    car.vendor_id 
FROM 
    car
    INNER JOIN dealers2cars ON car.id=dealers2cars.car_id
GROUP BY 
    car.vendor_id, 
    dealers2cars.`dealer_id`

答案 1 :(得分:0)

如果我正确地理解了这个问题,那么这应该适合你:

SELECT 
  count(vendor_id)
, dealers2cars.dealer_id
FROM dealers2cars JOIN car ON dealers2cars.dealer_id = car.id
GROUP BY dealer_id
HAVING COUNT(vendor_id) > 1

输出:

COUNT(VENDOR_ID)    DEALER_ID
2                   1
3                   2
2                   3

更新:这很可能是你需要的问题:

SELECT 
COUNT(DISTINCT(vendor_id)),dealer_id
FROM dealers2cars JOIN car ON dealers2cars.car_id = car.id
GROUP BY dealer_id
HAVING COUNT(DISTINCT(vendor_id)) > 1

它吸引了拥有超过1家独特供应商的汽车的经销商。