多个 select 计数在另一个 table

multiple select with count in another table

我有 3 个 Mysql 表: 产品(ID,名称) 用法(id,product_id) Usage_history(id, usage_id, status_id).

status_id 可以有 1 到 5 的值(从应用程序给定)。

我想搜索并找到使用过 status_id=1 次以上的所有产品。

试试下面的查询-

SELECT pr.id,pr.name,COUNT(uh.id) AS cnt
FROM usage_history uh 
JOIN `usage` us ON us.id=uh.usage_id 
JOIN products pr ON pr.id=us.product_id 
WHERE uh.status_id=1 
GROUP BY pr.id 
HAVING cnt>1;

你需要join,最后用conditional aggregationgroup by

过滤掉数据
select
p.* from products p
join `usage` u on u.product_id = p.id
join usage_history uh on uh.usage_id = u.id
group by p.id
having sum(uh.status_id = 1) > 1

http://www.sqlfiddle.com/#!9/52690/1