Mysql 嵌套计数

Mysql nested count

我有 3 个表相互连接

预订 > 出价 (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-04 的预订数是 7468,我收到 9359 预订,应该不超过它自己的预订数。

我认为您需要根据自己的需要采取不同的方法

仅select日期之间的所有预订并计算子查询中的预订 应该是这样的,但是根据给定的信息有点难测试

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