简体   繁体   中英

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

I need one help. I need to fetch all record from table by keeping its some value as max or min using MySQL. I am explaining my table and code below.

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

Here is my table.I am explaining my query below.

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

Here i can get 3 record from table as per condition. But i need to keep min(day1) and max(day2) value in each record. Means each record will contain the day1=1 and day2=3 as per the required condition and same 3 record should fetch. Please help me.

You could try using a subselect.

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

I think this is what you want

在此处输入图片说明

The following query will do the job.

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 

Here i have used coalesce() . You can read more about this function here

Mysql Docs
Oracle Docs

    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

Try this, hopefully it will help you... if your expectation is my attached image alike.

在此处输入图片说明

Please try with this

    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." ;

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