2012-11-01 58 views
0

您好我遇到了一個難題,我做這個查詢:只獲得從子選擇一個結果以內蒙古MySQL的加入

SELECT GROUP_CONCAT(DISTINCT(ca.category_name) SEPARATOR ', ') AS categories, pr.promo_name, pr.add_value_text, c.contract_id, c.cmeal_plan, c.cmin_markup, c.civa, c.tax_include, c.hotel_id, hi.hname, hi.hstars, im.image_file, pl.plan_name, ra.price 
FROM contracts AS c 
INNER JOIN hotel_info AS hi ON hi.hotel_id = c.hotel_id AND hi.destination_id = '6460' 
INNER JOIN images AS im ON im.foreign_id = hi.hotel_id 
INNER JOIN meal_plan AS pl ON pl.plan_code = c.cmeal_plan AND pl.lang = '1' 
INNER JOIN hotel_categories AS hc ON hc.hotel_id = hi.hotel_id 
INNER JOIN categories AS ca ON ca.category_code = hc.category_code AND ca.lang = '1' 
LEFT JOIN 
        (SELECT 
           r.hotel_id, AVG(r.double) AS price 
        FROM 
           rates AS r) AS ra 
        ON ra.hotel_id = hi.hotel_id 
LEFT JOIN promotions AS pr ON pr.hotel_id = hi.hotel_id AND FIND_IN_SET(c.contract_id, pr.contract_id) > 0 AND pr.book_start <= '2012-11-01' AND pr.book_end >= '2012-11-02' AND travel_start <= '2012-11-23' AND travel_end >= '2012-11-30' AND pr.lang = '1' 
WHERE c.cstart <= '2012-11-01' AND c.cend >= '2012-11-01' 
AND hi.status = '1' 
AND im.type ='1' 
GROUP BY hi.hotel_id 

我收到除分select查詢所需的全部結果。每個酒店都有一個價格,但它只是給我一個結果,其餘的都是空的。我的查詢中有錯誤嗎?如果需要任何其他信息,請讓我知道,並提前感謝您的幫助!

回答

1

您在子查詢中缺少GROUP BY,所以MySQL只會返回一個值。如果你想要所有hotel_id的話你需要GROUP BY那個字段:

SELECT GROUP_CONCAT(DISTINCT(ca.category_name) SEPARATOR ', ') AS categories, 
    pr.promo_name, 
    pr.add_value_text, 
    c.contract_id, 
    c.cmeal_plan, 
    c.cmin_markup, 
    c.civa, 
    c.tax_include, 
    c.hotel_id, 
    hi.hname, 
    hi.hstars, 
    im.image_file, 
    pl.plan_name, 
    ra.price 
FROM contracts AS c 
INNER JOIN hotel_info AS hi 
    ON hi.hotel_id = c.hotel_id 
    AND hi.destination_id = '6460' 
INNER JOIN images AS im 
    ON im.foreign_id = hi.hotel_id 
INNER JOIN meal_plan AS pl 
    ON pl.plan_code = c.cmeal_plan 
    AND pl.lang = '1' 
INNER JOIN hotel_categories AS hc 
    ON hc.hotel_id = hi.hotel_id 
INNER JOIN categories AS ca 
    ON ca.category_code = hc.category_code 
    AND ca.lang = '1' 
LEFT JOIN 
(
    SELECT r.hotel_id, AVG(r.double) AS price 
    FROM rates AS r 
    GROUP BY r.hotel_id <-- add a GROUP BY hotel_id then you will get avg() for each hotel 
) AS ra 
    ON ra.hotel_id = hi.hotel_id 
LEFT JOIN promotions AS pr 
    ON pr.hotel_id = hi.hotel_id 
    AND FIND_IN_SET(c.contract_id, pr.contract_id) > 0 
    AND pr.book_start <= '2012-11-01' 
    AND pr.book_end >= '2012-11-02' 
    AND travel_start <= '2012-11-23' 
    AND travel_end >= '2012-11-30' 
    AND pr.lang = '1' 
WHERE c.cstart <= '2012-11-01' 
    AND c.cend >= '2012-11-01' 
    AND hi.status = '1' 
    AND im.type ='1' 
GROUP BY hi.hotel_id 
+0

謝謝soooooo多!! – liveandream