比较 table 和 MySQL 中的行

Compare rows in one table with MySQL

我试图比较我拥有的 table 中的行。 table 是这样的:

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 行进行比较,它们的每一行都有相同的 fid 和不同的 id。问题是,我如何将其中三个与 return 进行比较?

例如,

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那么我们return它,而tp 2应该和[=17比较=] 如果 tp 1ct 大于 0 那么我们可以 return tp 2。如果 tp 2tp 1ct 大于 0 return tp 3。 (都一样fid

结果应该是这样的:

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

没有SQL我也能搞定这部分。我可以 return 所有行并将它们与 return 我想要的结果进行比较,但这不是一个好的解决方案,因为我只想用 MySQL.[=31 处理所有这部分=]

您似乎第一次想要 ct = 0 为每个 fid 基于 id。这表明:

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