我怎么能在一个mysql查询中执行此操作

时间:2012-04-10 11:35:40

标签: mysql

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查询。有什么想法吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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