2012-01-25 168 views
0

我有一個解析器來創建基於表單輸入的動態查詢,但現在我需要在字段backend_hotels_id上選擇DISTINCT,但仍然返回整行(即SELECT *會做什麼)MySQL Select distinct with dynamic where子句

我的一個動態的查詢如下:

SELECT * FROM `packages_sorted_YHZ` WHERE 
(
    `hotel_country` = 'Antigua and Barbuda' 
    AND `hotel_city` IN 
    (
     'Bolans','Mamora Bay','Saint Philip','St. John\'s' 
    ) 
)OR(
    `hotel_country` = 'Aruba' 
    AND `hotel_city` IN 
    (
     'Oranjestad','Palm/Eagle Beach' 
    ) 
) 
AND `package_type` = '9' 
AND `date_start` >= '2012-1-25' AND `date_start` <= '2012-12-19' 
AND `hotel_score_title` <= '4' 
AND `day` IN ('1','2','3','5','6','7') 
AND `package_duration` IN ('5','6','7','8','9') 
AND `adults_only` = 'y' 
AND `price_per_pax_after_tax` <= '10000' 
ORDER BY `deal_score` DESC, `date_start` DESC 
LIMIT 0,3; 

上述查詢返回預期3個全行,但都來自同一個酒店。

我想保持對兩列(deal_scoredate_start)的順序和從記錄與唯一backend_hotels_id

返回整個行我讀here說,「在條件WHERE子句只適用於爲了檢查兩行,你必須使用JOIN「

在某些情況下,我在9列(上)和22列之間有一個where子句。由於整個查詢是動態創建的,我必須爲每種可能性創建場景?還是有更簡單的方法?

+1

我認爲括號中有一些錯誤。可能靠近'OR' –

+0

謝謝,我已經修正了括號。實際的查詢要大得多,我把它縮小了。 –

+0

你到底在想什麼?每個酒店的最高deal_score和date_start然後排序,然後是前3個,或前3個酒店的列表不超過1行? – piotrm

回答

1

未經檢驗

你可以嘗試這樣的事情:

CREATE TEMPORARY TABLE TempTable 
SELECT * FROM `packages_sorted_YHZ` WHERE 
(
    `hotel_country` = 'Antigua and Barbuda' 
    AND `hotel_city` IN 
    (
     'Bolans','Mamora Bay','Saint Philip','St. John\'s') 
    ) 
)OR(
    `hotel_country` = 'Aruba' 
    AND `hotel_city` IN 
    (
     'Oranjestad','Palm/Eagle Beach' 
    ) 
) 
AND `package_type` = '9' 
AND `date_start` >= '2012-1-25' AND `date_start` <= '2012-12-19' 
AND `hotel_score_title` <= '4' 
AND `day` IN ('1','2','3','5','6','7') 
AND `package_duration` IN ('5','6','7','8','9') 
AND `adults_only` = 'y' 
AND `price_per_pax_after_tax` <= '10000' 
; 


SELECT * 
FROM TempTable 
WHERE 
    `deal_score` = (SELECT MAX(t1.deal_score) FROM TempTable AS t1 WHERE t1.backend_hotels_id = TempTable.backend_hotels_id) 
     AND `date_start` = (SELECT MAX(t2.date_start) FROM TempTable AS t2 WHERE t2.backend_hotels_id = TempTable.backend_hotels_id) 
    LIMIT 0,3; 

DROP TEMPORARY TABLE TempTable; 

PS:根據您的數據和索引你可以用子查詢做到這一點還沒有不是Temptable獲得更好的性能。

0

您想如何確定應該選擇同一組backend_hotel_id中的哪一行?

您可以使用GROUP BY backend_hotels_id,但我認爲它會顯示給您的酒店是任意的(或者至少您應該認爲它是任意的)。

+0

我想根據'ORDER BY'子句返回最高'deal_score'和'date_start'值的記錄,但每個記錄都帶有'UNIQUE backend_hotels_id' –