这有点难以解释,所以我会分解它......这是目标
假设您有一个表
ID | Weight
1 2
2 4
3 8
4 66
5 11
6 44
7 33
假设我有一组感兴趣的 ID,比如 (3,4)
我的目标是获取另外两行(两个感兴趣的 ID 各一行),以便与感兴趣的 ID 匹配的行的权重比感兴趣的 ID 的权重小一个级别
所以在这种情况下
对于 id 3,我们希望返回 ID 为 2 且权重为 4 的行,因为行 ID 2 是权重 (4) 小于行 ID 3 (8) 权重的第一行
对于 ID 4,我们希望返回 ID 为 6 且权重为 44 的行,因为行 ID 6 是权重 (44) 小于行ID 4 (66) 权重的第一行
您将如何在一个查询中使用mysql完成此操作,从而我们对感兴趣的ID使用IN()表示法.....
提出以下建议(显然使用我们的表作为表名)
SELECT id,weight FROM ourtable WHERE weight IN (SELECT MAX(t.weight) FROM ourtable t,ourtable t2 WHERE t.weight < t2.weight && t2.id IN (3,4) GROUP BY t2.id);
它给出以下结果
+----+--------+
| id | weight |
+----+--------+
| 2 | 4 |
| 6 | 44 |
+----+--------+
根据要求。
您可以选择按权重 desc 排序的行的第一行来解决此问题,该行的权重低于给定权重,在这种情况下,对于 mysql,如下所示:
select * from t where weight < (select weight from t where id = :id) order by weight desc limit 1
在遵循上述想法的 IN 语句中,您可以有类似的东西:
select * from (select id, (select weight from t where weight < (select weight from t where id = tp.id) order by weight desc limit 1) from t tp) a where id in (3,4)
另一个没有子查询的解决方案:
select w1.id,w1.weight,
left(group_concat(w2.id order by w2.id desc ),LOCATE(',', group_concat(w2.id order by w2.id desc ))-1) as w2_id,
left(group_concat(w2.weight order by w2.weight desc ),LOCATE(',', group_concat(w2.weight order by w2.weight desc ))-1) as w2_weight
from weight as w1, weight as w2
where w2.weight < w1.weight
and w1.id in (3,4)
group by w1.id