我有3个Mysql表: 产品(id,名称) 用法(id,product_id) Usage_history(id,usage_id,status_id)。
status_id的值可以是1到5(从应用程序中提供)。
我想搜索并查找已使用status_id = 1的所有产品,超过1次。
答案 0 :(得分:0)
尝试以下查询 -
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;
答案 1 :(得分:0)
您需要join
,最后使用conditional aggregation
group by
过滤掉数据{/ 1}}
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