2015-06-11 158 views
0

我有3个表彼此连接Mysql的嵌套计数

预订>出价(booking_id)> bid_participants(bid_id)

所以创建预订时,它将被喷砂和接收到大于0人或根本

收到什么,我想要实现计数预订,如果它超过0人接收,并认为这是1

SELECT 
    COUNT(b.id) as booking_count, 
    COUNT(if(COUNT(bip.bid_status) > 0, 1, 0)) as bid_received_count // this part 
    DATE(b.date_created) AS daily_booking 
FROM booking AS b 
JOIN booking_route AS br on b.id = br.booking_id 
JOIN bid AS bi on b.id = bi.booking_id 
JOIN bid_participant AS bip on bi.id = bip.bid_id 
WHERE 
DATE(b.date_created) BETWEEN '2015-06-04' AND '2015-06-10' 
AND br.service_type = 1 
AND bip.bid_status = 1 
GROUP BY daily_booking; 

这是只要我能得到

SELECT 
    COUNT(b.id) AS total_booking, 
    COUNT(CASE WHEN bip.bid_status > 0 THEN 1 END) AS bid_received_count, 
    br.service_type, 
    DATE(b.date_created) AS daily_booking 
FROM booking AS b 
JOIN booking_route AS br on b.id = br.booking_id 
JOIN bid AS bi on b.id = bi.booking_id 
JOIN bid_participant AS bip on bi.id = bip.bid_id 
WHERE 
DATE(b.date_created) BETWEEN '2015-06-04' AND '2015-06-10' 
AND br.service_type = 1 
AND bip.bid_status = 1 
GROUP BY daily_booking; 
AND br.service_type = 1 
AND bip.bid_status = 1 
group BY daily_booking; 

上面的查询与预订计数2015-06-047468,我得到接受9359预订,应该不超过预订更指望它的自我。

回答

0

我认为你需要做你想要

只需选择所有日期间的预订和计数的子查询 它应该是这样的有什么不同的方法,但它有点难以测试与给定的信息

SELECT 
    (SELECT count(*) 
     FROM booking AS b 
     JOIN booking_route AS br on b.id = br.booking_id 
     JOIN bid AS bi on b.id = bi.booking_id 
     JOIN bid_participant AS bip on bi.id = bip.bid_id 
     WHERE bip.bid_status > 0 
      AND DATE(b.date_created) BETWEEN '2015-06-04' AND '2015-06-10' 
      AND br.service_type = 1 
      AND bip.bid_status = 1 
     GROUP BY daily_booking; 
      AND br.service_type = 1 
      AND bip.bid_status = 1 
      group BY daily_booking) AS bid_received_count 
+0

是经过多次尝试,我想我需要的是子查询,谢谢 – littlechad