我有三个数据库表:
门票:它包含两个columns id
,title
优惠:它包含三个columns id
,title
,ticket_id
,accepted_offer_id
接受的优惠:它包含两个columns id
,result
accepted_offer_id
是accepted_offer
ticket_id
是Tickets
我让我的用户添加门票,每张门票都包含很多优惠,每个优惠最终都会有结果赢或丢失或取消或等待。
如果没有等待优惠(所有优惠已赢或丢失或取消),则认为票已完成。我想计算所有门票已经结果(不等待)的所有门票的成品门票数count(id) from tickets
。
我可以使用以下查询来获取所有已完成的票证,但直到现在使用count
函数的单个查询我才算数:
SELECT t.id,
o.ticket_id,
sum(case when a.result = 0 then 1 else 0 end) as ticket_status
FROM offers o
INNER JOIN accepted_offers a ON a.id = o.accepted_offer_id
INNER JOIN tickets t ON t.id = o.ticket_id
WHERE t.user_id = $user_id
GROUP BY o.ticket_id HAVING ticket_status = 0
每个0添加到总和意味着此优惠处于等待状态,因此对于每个票证,如果ticket_status等于零,则表示它没有等待的优惠被视为已完成的票证
我想使用count
函数直接查找已完成票证的计数,而不会提供所有这些信息。有可能吗?
答案 0 :(得分:0)
SELECT t.id,
o.ticket_id,
count(if(a.result = 0)) as ticket_status
FROM offers o
INNER JOIN accepted_offers a ON a.id = o.accepted_offer_id
INNER JOIN tickets t ON t.id = o.ticket_id
WHERE t.user_id = $user_id
GROUP BY o.ticket_id HAVING ticket_status = 0
试试这个