用MySQL比较一个表中的行



我试图比较我拥有的一个表中的行。表是这样的:

table

id - fid - tp - ct
11 - 222 - 1 - 1
12 - 222 - 2 - 0
13 - 222 - 3 - 0
14 - 333 - 1 - 3
15 - 333 - 2 - 2
16 - 333 - 3 - 0
17 - 555 - 1 - 2
18 - 444 - 1 - 0
19 - 555 - 2 - 0
20 - 444 - 2 - 0
21 - 444 - 3 - 0
22 - 555 - 3 - 0

我有3行比较,他们有tp 1,2,3每一个具有相同的fid和不同的id。问题是,我如何比较它们中的三个?

例如,

if (t1 == 0){ // check t1
   return t1;
}else if (t1 > 0 AND t2 == 0){ // check t2
   return t2;
}else if (t1 > 0 AND t2 > 0 AND t3 == 0){ // check t3
   return t3;
}

更多解释

例如,如果tp 1ct等于0,那么我们返回它,如果tp 1ct大于0,那么tp 2应该与tp 1比较,所以我们可以返回tp 2。如果tp 2tp 1中的ct大于0,则返回tp 3。(它们都有相同的fid)

结果应该是这样的:

===================
id | fid | tp | ct
-------------------
12 | 222 | 2  | 0
-------------------
16 | 333 | 3  | 0
-------------------
18 | 444 | 1  | 0
-------------------
19 | 555 | 2  | 0
===================

我可以处理这部分没有SQL。我可以返回所有行并比较它们并返回我想要的结果,但这不是一个好的解决方案,因为我只想用MySQL处理所有这些部分。

您似乎希望第一次将ct = 0用于每个基于id的fid。这表明:

select t.*
from (select t.*,
             row_number() over (partition by fid order by id) as seqnum
      from t
      where ct = 0
     ) t
where seqnum = 1;

编辑:

在旧版本的MySQL中,你可以使用:

select t.*
from (select t.*,
             (select min(t2.id)
              from t t2
              where t2.ct = 0 and t2.fid = t.fid
             ) as min_id
      from t
      where ct = 0
     ) t
where id = min_id

可以这样使用not exists:

Select t.* from your_table t
 Where not exists
       (Select 1 from your__table tt
         Where tt.fid = t.fid and tt.tp < t.tp and tt.ct = 0)
  And t.ct = 0

最新更新