我有一个查询应该从每个price_per_pax_after_tax
backend_hotels_id
和date_start
中选择最低的package_supplier
,这似乎一直有效,直到我添加一个WHERE子句。
以下是查询:
SELECT e.price_per_pax_after_tax, e.hotel_score, e.package_id, e.package_type
FROM packages_sorted_YQU e
INNER JOIN (
SELECT db_id, MIN( price_per_pax_after_tax ) AS lowest_price, package_id, hotel_score
FROM `packages_sorted_YQU`
WHERE `package_type` IN ('9', '10', '18')
AND `package_duration` IN ('6', '8', '12')
GROUP BY
`date_start` , `package_supplier` , `backend_hotels_id`
) AS j
ON j.db_id = e.db_id
AND j.lowest_price= e.price_per_pax_after_tax
AND j.hotel_score = e.hotel_score
AND j.package_id = e.package_id;
表格很大但列出的所有字段都是INT,除了date_start
是DATE
导致问题的where子句是:
WHERE `package_type` IN ('9', '10', '18')
AND `package_duration` IN ('6', '8', '12')
如果没有where子句,我会获得超过400个结果,并且使用where子句我得到零结果:(非常感谢任何帮助。
答案 0 :(得分:1)
如果您的列package_type
和package_duration
的类型为int
,则不必像'
那样将值包装在字符串中。
SELECT e.price_per_pax_after_tax, e.hotel_score, e.package_id, e.package_type
FROM packages_sorted_YQU e
INNER JOIN (
SELECT db_id, MIN( price_per_pax_after_tax ) AS lowest_price, package_id, hotel_score
FROM `packages_sorted_YQU`
WHERE `package_type` IN (9, 10, 18)
AND `package_duration` IN (6, 8, 12)
GROUP BY
`date_start` , `package_supplier` , `backend_hotels_id`
) AS j
ON j.db_id = e.db_id
AND j.lowest_price= e.price_per_pax_after_tax
AND j.hotel_score = e.hotel_score
AND j.package_id = e.package_id;
答案 1 :(得分:0)
子查询:
SELECT db_id
, MIN( price_per_pax_after_tax ) AS lowest_price
, package_id
, hotel_score
FROM `packages_sorted_YQU`
WHERE `package_type` IN ('9', '10', '18')
AND `package_duration` IN ('6', '8', '12')
GROUP BY
`date_start`
, `package_supplier`
, `backend_hotels_id`
无论是否有WHERE
子句,都会产生不确定的结果。因为您按date_start, package_supplier, backend_hotels_id
进行分组,并且在SELECT
列表列中没有任何汇总函数:db_id, package_id, hotel_score
。
如果(date_start, package_supplier, backend_hotels_id)
是主键或唯一,则此查询应始终如一。
哪个是表格的PRIMARY KEY
,还有其他UNIQUE
个密钥吗?
答案 2 :(得分:0)
大家好,感谢您的宝贵意见。我已经在没有子查询的情况下解决了问题,而且它的工作速度也快了。
SELECT MIN
(
concat
(
LPAD(`price_per_pax_after_tax` , 5, '0'),
LPAD(`package_id` , 12, '0'),
LPAD(`hotel_score` , 7, '0')
)
) AS cat
FROM `packages_sorted_YQU`
WHERE `package_type` IN
(
9, 10, 18
)
AND `package_duration` IN
(
6, 7, 8
)
GROUP BY `date_start` , `package_supplier` , `backend_hotels_id`
然后在PHP中我将串联分解为:
while($r=mysql_fetch_array($q,MYSQL_ASSOC))
{
$a[lrp][] = intval(substr($r[cat], 0, 5));
$a[package_id][] = intval(substr($r[cat], 5, 12));
$a[hotel_score][] = substr($r[cat], 17, 7);
}
我很幸运,唯一的FLOAT值是hotel_score
所以我把它放在最后 - 其他两个是INT类型