有两个表:
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;
和返回某些行的基本查询
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
个产品行的数量?
感谢。
答案 0 :(得分:0)
只需将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
子句中的别名。