我需要使用PHP和MySQL按照列值过滤表中的值。我正在解释下面的表格和代码。
db_images:
image_id member_id subcat_id from_day to_day
1 220 56 1 3
2 220 56 1 3
3 220 56 1 1
4 120 22 1 5
5 120 22 2 4
我在下面解释我的问题。
$qry=mysqli_query($connect,"select * from db_iamges group by member_id,subcat_id order by image_id desc");
使用我的查询我得到一条如下记录。
image_id member_id subcat_id from_day to_day
3 220 56 1 1
在这里,我需要to_day
应该始终具有更高的价值。如果存在相同的member_id and subcat_id
,则to_day将始终为更高的值,而from_day将始终为更小的值。预期的输出应如下所示。
image_id member_id subcat_id from_day to_day
1 220 56 1 3
4 120 22 1 5
答案 0 :(得分:1)
看起来你有语法问题,因为如果你复制粘贴,就把" db_iamges&#34 ;.我做了一张桌子:
mysql> select * from prueba1;
+----------+-----------+-----------+----------+--------+
| image_id | member_id | subcat_id | from_day | to_day |
+----------+-----------+-----------+----------+--------+
| 1 | 220 | 56 | 1 | 3 |
| 2 | 220 | 56 | 1 | 3 |
| 3 | 220 | 56 | 1 | 1 |
| 4 | 120 | 22 | 1 | 5 |
| 5 | 120 | 22 | 2 | 4 |
| 6 | 120 | 22 | 2 | 9 |
| 7 | 120 | 22 | 2 | 2 |
+----------+-----------+-----------+----------+--------+
7 rows in set (0.00 sec)
和
mysql> select image_id, member_id, subcat_id, min(from_day), max(to_day) from prueba1 group by member_id, subcat_id order by image_id asc;
+----------+-----------+-----------+----------+-------------+
| image_id | member_id | subcat_id | from_day | max(to_day) |
+----------+-----------+-----------+----------+-------------+
| 1 | 220 | 56 | 1 | 3 |
| 4 | 120 | 22 | 1 | 9 |
+----------+-----------+-----------+----------+-------------+
2 rows in set (0.00 sec)
它正在运作
编辑:已更新,因为我不了解您的主要问题。
答案 1 :(得分:0)
Select
T.*
From db_images t
Inner join (
Select member_id, subcat_id, max(to_day) to_day
db_images group by member_id,subcat_id
) t2 on t.member_id = t2.member_id
And t.Subcat_id = t2.subcat_id
And t.to_day = t2.to_day;
答案 2 :(得分:0)
使用max(列名)获得更高的值。
select image_id, member_id,subcat_id,from_day, max(to_day) as to_day from from db_iamges group by member_id,subcat_id order by image_id desc
答案 3 :(得分:0)
试试这个
select t1.* from db_images t1 inner join(select max(member_id) as
mid,max(subcat_id) as cid,min(from_day) as fdy from db_images group
by member_id) t2 on t1.member_id = t2.mid and t2.cid = t1.subcat_id
and t2.fdy = t1.from_day group by member_id order by image_id asc;