繁体   English   中英

如何使用MySQL和PHP从保持最大,最小列值的表中获取值

[英]How to fetch value from table keeping max,min column value using MySQL and PHP

我需要一个帮助。 我需要通过使用MySQL将其某些值保持为max或min来从表中获取所有记录。 我在下面解释我的表和代码。

db_images:

id        member_id        day1       day2      images

1           241             1          1         asc.png

2           241             1          2         xzc.png

3           241             2          3         ohjy.png

4          240             1           5         asd.png

这是我的桌子。我在下面解释我的查询。

$member_id=241
$qry=mysqli_query($connect,"select * from db_images where member_id='".$member_id."'");

在这里我可以根据条件从表中获得3条记录。 但是我需要在每个记录中保留min(day1) and max(day2)值。 意味着每个记录将根据所需条件包含day1=1 and day2=3 ,并且应提取相同的3条记录。 请帮我。

您可以尝试使用子选择。

select minday1, maxday2, t1.id, t2.member_id, t1.images
from (select min(day1) as minday1, max(day2) as maxday2, member_id from db_images 
group by member_id) as t2, db_images  as t1
where t2.member_id = t1.member_id and t1.member_id=$member_id

我想这就是你想要的

在此处输入图片说明

以下查询将完成这项工作。

select id,coalesce((select min(day1) from db_images where member_id=241)) as day1,
coalesce((select max(day2) from db_images where member_id=241)) as day2,
images from db_images where member_id=241 

在这里,我使用了coalesce() 您可以在此处阅读有关此功能的更多信息

Mysql文档
Oracle文档

    Select A.*,B.DAY_2 From 
    (Select id,member_id,images,min(day1) as DAY_1 From db_images where member_id=241 group by member_id) as A
    Inner Join
    (Select id,member_id,images,max(day2) as DAY_2 From db_images where member_id=241 group by member_id) as B

尝试一下,希望它能对您有所帮助...如果您的期望与我所附的图像相同。

在此处输入图片说明

请尝试这个

    SELECT * , 
    (select MIN(`day1`) from `db_images` where member_id = ".$member_id.") as minDay ,    
    (select MAX(`day2`) from `db_images` where member_id= ".$member_id.") as maxDay 
    FROM `db_images` WHERE `member_id` = ".$member_id." ;

暂无
暂无

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

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