[英]How to get the max and min of a data from child table with mysql and php?
使用max()和min()聚合函數,對於max檢查是否與min相同,如果相同,則返回null:
select data, min(sub_data), if(min(sub_data)=max(sub_data), null, max(sub_data)
from parent p
inner join child c on p.id=c.p_id
對於您的第一件事:
SELECT
p.data, c.sub_data, c.`datetime`
FROM parent p
JOIN child c
ON p.id = c.pid
JOIN (
SELECT max(`datetime`) as `datetime`, pid
FROM child
GROUP BY pid
) c1
on p.id = c1.pid AND c.`datetime` = c1.`datetime`;
第二件事是:
SELECT
p.data,
cmin.sub_data as Min(sub_data),
case when cmin.sub_data = cmax.sub_data then null else cmax.sub_data end as Min(sub_data)
FROM parent p
JOIN (
SELECT max(`datetime`) as `maxdatetime`, min(`datetime`) as `mindatetime`, pid
FROM child
GROUP BY pid
) c
on p.id = c1.pid
JOIN child cmax
ON p.id = cmax.pid AND c.`maxdatetime` = cmax.`datetime`
JOIN child cmin
ON p.id = cmin.pid AND c.`mindatetime` = cmin.`datetime`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.