我有以下表格,TABLE1
ID1 ID2 Count1 Count2 Count3
aaaaa bbbbb 1 1 0
ccccc dddd 2 2 0
eeee fffff 3 3 0
gggg hhhh 4 4 0
和表2
ID1 ID2 Count1 Count2 Count3
bbbbb aaaaa 5 5 5
dddd ccccc 4 4 4
fffff eeee 3 3 3
aaaaaa gggg 2 2 2
现在我要添加count1和count3并将其称为新count4,条件是table1.id1 = table2.id2和table2.id1 = table1.id2。
我知道必须使用的情况,但我不确定加入。
决赛桌应该是这样的
ID1 ID2 Count4 Count2 Count3
aaaaa bbbbb 6 1 0
ccccc dddd 6 2 0
eeee fffff 6 3 0
gggg hhhh 4 4 0
可能有其他行,其count3>表1中的0
答案 0 :(得分:0)
您必须使用INNER JOIN连接这两个表并使用算术运算来执行求和:
SELECT(t1.count1 + t2.count3)AS count4,t1.count1,t1.count3 FROM table1 as t1 INNER JOIN table2 as t2 WHERE t1.id2 = t2.id
参考文献:https://dev.mysql.com/doc/refman/5.0/en/arithmetic-functions.html 并且:https://dev.mysql.com/doc/refman/5.0/en/join.html
答案 1 :(得分:0)
在这种情况下,取决于id的count1的总和有点复杂,所以你可能需要先使用left join和group by来获取计数,最后将table1连接到结果的某些部分为
select
t1.ID1,
t1.ID2,
coalesce(x.Count1,t1.Count1) as Count4,
t1.Count2,
t1.Count3
from table1 t1
left join (
select
x1.ID1,
sum(x1.Count1+x2.Count1) as Count1
from table1 x1
left join Table2 x2 on x1.ID1 = x2.ID2 and x1.ID2=x2.ID1
group by x1.ID1
)x on x.ID1 = t1.ID1