我目前有两张桌子需要加入。
第一张表是一张大表,数百万条记录。第二个是匹配表。 我想加入2桌。预期结果的表格如下所示。 我需要有关如何编写SQL以加入2个表的提示。
Table 1
ID X Column X
1 X1
2 X2
3 X3
4 X4
5 X5
6 X6
... ...
the list goes on
Table 2
ID Column Y
1 Y1
3 Y2
6 Y3
11 Y4
Intended result
ID X Column X Column Y
1 X1 Y1
2 X2 Y1
3 X3 Y2
4 X4 Y2
5 X5 Y2
6 X6 Y3
7 X7 Y3
8 X8 Y3
9 X9 Y3
10 X10 Y3
11 X11 Y4
12 X12 Y4
答案 0 :(得分:4)
SELECT idX, columnX, columnY
FROM (
SELECT id, columnY, @prevID AS prevID, @prevID := id
FROM table2
CROSS JOIN (SELECT @prevID := NULL) init
ORDER BY id DESC) AS t2
JOIN table1 AS t1 ON t1.idX >= t2.id AND (t2.prevID IS NULL OR t1.idX < t2.prevID)
答案 1 :(得分:-1)
SELECT T1.IDX, T1.ColumnX , T2.ColumnY FROM TABLE1 T1
INNER JOIN TABLE2 T2 ON T1.IDX = T2.ID
答案 2 :(得分:-1)
我想要获得你需要使用内连接的预期结果:
select t1.id, t1.X, t2.Y from table1 t1 inner join table2 t2 on t1.id = t2.id;
用户链接:
http://blog.sqlauthority.com/2009/04/13/sql-server-introduction-to-joins-basic-of-joins/
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
编辑:
哦,我没有检查行不匹配。我试过这种方式。它对我有用:
select t1.id, t1.x,
if(t2.y != 'null',t2.y,(select y from table2 t3 where t3.id < t1.id order by t3.id desc limit 1)) as 'y'
from table1 t1 left join table2 t2 on t1.id = t2.id;