2015-06-11 195 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