0

这个问题的第一部分昨天在这里得到了一些很好的帮助,但我今天一直在努力完成我需要的查询。我试图根据某些条件从 5 个连接表中提取多列,但我希望结果集每个 p.id 仅包含一个不同的“数据条目”(宠物 ID,它是数据条目表中的外键) - 这个 data_entry 应该是具有该 p.id 的所有 data_entries 中数量最多的(即特定宠物的 data_entries 编号可能为 1,2 和 3 - 我只想要编号 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 的“更新”列执行日期比较,而是检查最低的数字。

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

编辑:最新尝试-导致“有子句”中的未知列“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
4

1 回答 1

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
于 2010-08-13T19:43:44.043 回答