2012-04-10 131 views
0
user table 
======== 
id(int) | name(varchar) 
------------------------ 
1  | user1 
2  | some_other_user 



product table 
=============== 
id(int) | user_id(int) | product(varchar) | status(varchar) 
------------------------------------------------------------ 
1  | 1   | product1   | bought 
2  | 1   | product3   | sold 
3  | 2   | product22  | sold 
4  | 2   | product2   | bought 
5  | 2   | product4   | sold 
6  | 1   | product5   | bought 
7  | 1   | product7   | sold 

我需要獲取用戶的姓名,他有多少產品,多少這些產品都這樣做有一個status = sold,用一個單一的MySQL查詢。有任何想法嗎?我怎麼能在一個MySQL查詢

+1

'status'應該是標準化的:你是在浪費分貝的空間,你很容易犯錯誤... – Marco 2012-04-10 11:40:17

回答

1

嘗試以下查詢:

select 
    u.id, 
    u.name, 
    count(p.product) as totalproducts, 
    sum(case when p.status = 'sold' then 1 else 0 end) as soldproducts 
from user u 
inner join product p on u.id=p.user_id 
group by u.id, u.name 
1

嘗試這個

SELECT u.id, u.name, 
COUNT(p.id) AS totalproducts, 
COUNT(IF(p.status="sold",p.user_id,NULL)) 
FROM users u 
INNER JOIN products p ON p.user_id = u.id 
GROUP BY u.id