简体   繁体   中英

How to get the max and min of a data from child table with mysql and php?

Lets take an example:

I have 2 tables as below

数据库中的主表

Child table is related to parent table using P_Id.

Parent table contains one row for each case. Child table stores actions on each case and related by P_id, datetime colums records the time of action.

Now, I want to query what is the max of each case , as below

max表的结果

Second thing I want to get is max and min of each case in same table can it be done by only mysql or do i have to do using php also.

Result that I expect is as below:

每种情况的最大和最小结果

Like this there are 1000's of rows in the table. Do i need to use python or something else to process this kind of data.

Use max() and min() aggregate functions and for max check if it is the same as min and return null if they are the same:

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

For your first thing:

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`;

and second thing is:

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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM