Group-wise-max - 分层数据查询帮助

时间:2010-08-13 17:35:50

标签: mysql group-by greatest-n-per-group groupwise

这个问题的第一部分昨天通过一些很好的帮助解决了,但我今天一直在努力完成我需要的查询。我试图根据一些条件从5个连接表中提取多个列,但我希望结果集每个p.id只包含一个不同的“数据条目”(pet id是数据输入表中的外键) - 此data_entry应该具有该p.id的所有data_entries的最大数量(即特定宠物可以具有编号为1,2和3的data_entries - 我只想要数字3)。我在下面的代码在第一个查询中正常工作,但我想添加一个附加子句来检查返回的最大记录的“更新”日期,但我似乎无法弄清楚如何正确地集成此子句。

非常感谢任何帮助:

此简化查询在3个连接表中正确工作(没有日期比较子句)

SELECT `p`.`id`, `o`.`id`, `o`.`email`, MAX(d.number) 
FROM (`pets` AS `p`, `owners` AS `o`, `data_entries` AS `d`) 
WHERE `p`.`owner_id` = `o`.`id` 
AND `p`.`id` = `d`.`pet_id` 
GROUP BY `p`.`id`, `o`.`id`, `o`.`email` 
ORDER BY `d`.`number` DESC 

但是,当我尝试添加下面的日期比较子句和额外表之间的连接时,查询不会对具有MAX编号的data_entry的“updated”列执行日期比较,而是检查最低的数字。

SELECT `p`.`id` AS `pet_id`, `o`.`id` AS `owner_id`, `o`.`email`, MAX(d.number) 
FROM (`pets` AS `p`, `owners` AS `o`, `data_entries` AS `d`, `k_records_owners` AS `kcro`, `k_records` AS `kcr`) 
WHERE `p`.`owner_id` = `o`.`id` 
AND `p`.`id` = `d`.`pet_id` 
AND `p`.`kc_number` = `kcr`.`do_dg_dog_no` 
AND `kcr`.`pa_breeder_no` = `kcro`.`contact_no` 
AND FROM_UNIXTIME(`d`.`updated`, "%Y-%m-%d") <= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 25 day), "%Y-%m-%d") 
GROUP BY `p`.`id`, `o`.`id`, `o`.`email` 
ORDER BY MAX(d.number) DESC

编辑:最新尝试 - 导致'having子句'中的未知列'd2.updated'

SELECT p.id AS pet_id, o.id AS owner_id, o.email, MAX(d.number) as max_d, d.updated 
FROM (pets AS p, owners AS o, data_entries AS d, data_entries AS d2, kennel_club_records_owners AS kcro, kennel_club_records AS kcr)
WHERE p.owner_id = o.id 
AND p.id = d.pet_id 
AND p.kc_number = kcr.do_dg_dog_no 
AND kcr.pa_breeder_no = kcro.contact_no 
AND d.number = d2.number
GROUP BY p.id, o.id, o.email 
having FROM_UNIXTIME(d2.updated, '%Y-%m-%d') <= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 25 day), '%Y-%m-%d') 
ORDER BY max_d DESC

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT p.id AS pet_id, o.id AS owner_id, o.email, MAX(d.number) as max_d, d.updated 
FROM (pets AS p, owners AS o, data_entries AS d, data_entries AS d2, kennel_club_records_owners AS kcro, kennel_club_records AS kcr)
WHERE p.owner_id = o.id 
AND p.id = d.pet_id 
AND p.kc_number = kcr.do_dg_dog_no 
AND kcr.pa_breeder_no = kcro.contact_no 
AND d2.number = max_d
AND FROM_UNIXTIME(d2.updated, '%Y-%m-%d') <= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 25 day), '%Y-%m-%d') 
GROUP BY p.id, o.id, o.email 
ORDER BY max_d DESC