简体   繁体   English

如何使用mysql和php从子表中获取数据的最大值和最小值?

[英]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 我有2张桌子如下

数据库中的主表

Child table is related to parent table using P_Id. 子表使用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. 子表存储每种情况下的操作,并通过P_id进行关联,datetime列记录操作时间。

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. 我想得到的第二件事是在同一个表中每种情况的最大值和最小值可以通过mysql来完成,或者我也必须使用php来完成。

Result that I expect is as below: 我期望的结果如下:

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

Like this there are 1000's of rows in the table. 像这样,表中有1000行。 Do i need to use python or something else to process this kind of data. 我需要使用python或其他方法来处理此类数据吗?

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: 使用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

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`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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