以间隔为基础加入两个表

时间:2015-05-01 18:25:30

标签: mysql sql

在SQL中,假设我有表A

ID
--
1
3
5

和表B

ID2
---
1
2
3
4
5
6

要获得类似的结果:

ID |  ID2
----------
1  |  1
1  |  2
3  |  3
3  |  4
5  |  5
5  |  6

为了便于说明,列ID2中的元素将映射到列ID中的最大值,该值小于或等于ID2中的所述元素。

例如,列ID2中的4从列ID映射到3,因为3是列ID中的最大值,小于或等于4.

是否有可能在sql中执行此操作?

3 个答案:

答案 0 :(得分:2)

我要做的是首先加入两个表,条件是第一个表中的id小于或等于第二个表中的id,如下所示:

SELECT t1.id, t2.id AS id2
FROM t1
JOIN t2 ON t2.id >= t1.id;

有了这个,你可以从第一个表中选择最大id,然后按第二个表中的id分组以获得最大的对:

SELECT MAX(t1.id) AS id, t2.id AS id2
FROM t1
JOIN t2 ON t2.id >= t1.id
GROUP BY t2.id;

SQL小提琴似乎已关闭,但我会尽快更新链接。

答案 1 :(得分:1)

SELECT MAX(A.ID) ID, B.ID2
FROM A
INNER JOIN B ON B.ID2 >= A.ID
GROUP BY B.ID2

答案 2 :(得分:1)

如果您只需要匹配的ID列:

myImageView.animationImages = [NSArray arrayWithObjects:
                              [UIImage imageNamed:@"image1.png"],
                              [UIImage imageNamed:@"image2.png"], nil];
[myImageView setAnimationRepeatCount:0];
myImageView.animationDuration = 2;
[myImageView startAnimating];

如果您需要更多列:

select b.*,
  (select max(ID) from a where a.ID <= b.ID2) as a_Id
from b
相关问题