MySQL选择distinct与dynamic where子句

时间:2012-01-25 17:49:37

标签: php mysql

我有一个基于表单输入创建动态查询的解析器,但现在我需要在字段backend_hotels_id上选择DISTINCT,但仍然返回整行(即SELECT *会做什么)

我的一个动态查询如下:

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;

上述查询按预期返回三行,但都来自同一家酒店。

我想在两列(deal_scoredate_start)上维护订单,并从具有唯一backend_hotels_id

我读到here“WHERE子句的条件一次只适用于一行。为了检查两行,你必须使用JOIN”

在某些情况下,我在9列(上面)和22列之间有一个where子句。由于整个查询是动态创建的,我是否必须为每种可能性创建场景?或者有更简单的方法吗?

2 个答案:

答案 0 :(得分: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:根据您的数据和索引,您也可以使用子查询来执行此操作,而不会产生更高的性能。

答案 1 :(得分:0)

您想如何确定应该选择同一组backend_hotel_id中哪一行?

您可以使用GROUP BY backend_hotels_id,但我认为它会告诉您的酒店是任意的(至少您应该认为它是随意的)。