这是有效的SQL吗?使用GROUP BY
也是正确的吗?
另外,我如何按TOTAL排序结果?
由于
SELECT packages.id AS PPIIDD,
Q_ALLOTMENTS.total AS TOTAL,
roomname,
hotelrooms.room_id AS RID,
packages.description AS PDESC,
hotelname,
regionname,
places.name AS PLACENAME,
destinationname,
hotels.property_desc,
hotels.hotel_id AS HID,
room_rates.high AS ROOM_HIGH,
packages.low AS PLOW,
hotels.startype,
address1,
address2,
town,
postcode,
hotelrooms.room_id AS RID,
packages.type AS PTYPE
FROM packages
INNER JOIN hotels
ON hotels.hotel_id = packages.hotel_id
AND hotels.status = 'active'
INNER JOIN allotments_new
ON allotments_new.package_id = packages.id
AND allotments_new.day_date >= '2013-04-17'
AND allotments_new.day_date < '2013-04-18'
AND allotments_new.day_rate > 0
AND allotments_new.status != 'n'
AND allotments_new.minimum_number_of_nights <= 1
INNER JOIN hotelrooms
ON hotelrooms.room_id = packages.room_id
AND hotelrooms.status = 'active'
INNER JOIN room_rates
ON room_rates.room_id = hotelrooms.room_id
INNER JOIN destinations
ON destinations.destination_id = hotels.destination_id
INNER JOIN regions
ON regions.region_id = hotels.region_id
LEFT OUTER JOIN places
ON places.id = hotels.places_id
INNER JOIN (SELECT Sum(day_rate) AS TOTAL,
allotments_new.status,
allotments_new.number_of_rooms,
day_rate,
day_date,
package_id
FROM allotments_new
WHERE allotments_new.day_date >= '2013-04-17'
AND allotments_new.day_date < '2013-04-18'
AND allotments_new.day_rate > 0
AND allotments_new.status != 'n'
AND allotments_new.minimum_number_of_nights <= 1
GROUP BY allotments_new.status,
allotments_new.number_of_rooms,
day_rate,
day_date,
package_id) AS Q_ALLOTMENTS
ON Q_ALLOTMENTS.package_id = packages.id
WHERE hotels.hotel_id = '1875'
AND packages.status = 'active'
AND hotels.status = 'active'
AND hotelrooms.status = 'active'
AND maximum_number_of_adults_and_children >= '1'
AND 1 = '1'
AND 1 = '1'
AND 1 = '1'
AND 1 = '1'
AND 1 = '1'
AND 1 = 1
AND 1 = 1
GROUP BY ppiidd
ORDER BY startype DESC
答案 0 :(得分:3)
Mysql有一种特殊的处理组的方法,因为任何其他数据库都不支持AFAIK。这是:
通常,group by必须列出未聚合的所有列。但是在mysql中,mysql的行为不是抛出错误,而是为group by子句中列出 列的每个唯一组合返回一行,随机选择。实际上,选择的行不是随机的,而是遇到第一个行。
答案是它不是错误,但查询可能无法返回您期望的结果。
顺便说一下,这个功能非常方便根据列的某个子集获取第一行/最后一行,例如获取每个项目的最新行:
select * from (
select * from mytable order by timestamp desc) x
group by item_id
中间查询确保首先在最新的时间戳顺序中遇到行。 funky group by返回每个item_id遇到的第一行,这当然是最新的。