2017-12-22 28 views
-1

을 갖는 필터링 된 행을 계산 두 개의 테이블이있다 : 나는 p.id 당 제품 행의 수를 셀 수있는 방법 일부 행 MYSQL :

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) 

을 반환

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; 

및 기본 쿼리?

감사합니다.

+1

예상 행 개수는 – 2oppin

+0

입니다. https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me를 참조하십시오. -to-be-be-a-very-simple-sql-query – Strawberry

+0

id 단위 또는 전체 행 수를 의미합니까? – Barmar

답변

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 절의 별칭을 참조 할 수도 있습니다.