我需要一个帮助。我需要通过使用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条记录。请帮帮我。
答案 0 :(得分:1)
您可以尝试使用子选择。
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
答案 1 :(得分:1)
我认为这就是你想要的
以下查询将完成此任务。
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()
。
您可以在这里阅读有关此功能的更多信息
答案 2 :(得分:0)
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
试试这个,希望它会对你有所帮助......如果你的期望是我的附图。
答案 3 :(得分:0)
请尝试使用此
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." ;