MYSQL:用 having 计算过滤后的行数

MYSQL: count filtered rows with having

有两个表:

CREATE TABLE `products` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`price` decimal(10,2) unsigned NOT NULL,
`quantity` smallint(5) unsigned NOT NULL,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `products_item` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`product_id` int(10) unsigned NOT NULL,
`quantity` smallint(6) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

和 return 一些行的基本查询

select p.id, p.quantity, sum(pi.quantity) as pi_quantity
from products p
left join products_item pi on pi.product_id=p.id
group by p.id
having p.quantity > sum(pi.quantity)

如何计算每个 p.id 的产品行数?

谢谢。

只需在查询中添加 COUNT(pi.id)

select p.id, p.quantity AS quantity, sum(pi.quantity) as pi_quantity, COUNT(pi.id) AS pi_count
from products p
left join products_item pi on pi.product_id=p.id
group by p.id
having quantity > pi_quantity

您也可以在HAVING子句中引用别名。