【发布时间】:2020-11-25 19:15:50
【问题描述】:
我有 2 个要加入的表,但查询有时会在另一行匹配。
表 t1
+-----+
| Re |
+-----+
| 123 |
| 321 |
+-----+
表table2
+-----+-----+-----+-----+
| Re | Re2 | Cla | Val |
+-----+-----+-----+-----+
| 123 | abc | RV | 10 |
| 123 | cba | AB | 5 |
| 321 | xyz | ZV | 4 |
| 321 | zyx | RV | 6 |
+-----+-----+-----+-----+
查询
select t1.Re,t2.Re2, sum(t2.Importeenmonedalocal) as Sum, from table t1
left join table2 as t2 on
t2.Re LIKE CONCAT('%',t1.Re,'%')
group by t1.Re;
实际结果:
+-----+-----+-----+
| Re | Re2 | Sum |
+-----+-----+-----+
| 123 | cba | 15 |
| 321 | xyz | 10 |
+-----+-----+-----+
预期结果:
当Cla='RV' 像这样时,我期望的是 t2 中的连接匹配:
+-----+-----+-----+
| Re | Re2 | Sum |
+-----+-----+-----+
| 123 | abc | 15 |
| 321 | zyx | 10 |
+-----+-----+-----+
我尝试像这样添加where:
select t1.Re,t2.Re2, sum(t2.Importeenmonedalocal) as Sum, from table t1
left join table2 as t2 on
t2.Re LIKE CONCAT ('%',t1.Re,'%')
where t2.Cla='RV'
group by t1.Re;
但总和不正确:
+-----+-----+-----+
| Re | Re2 | Sum |
+-----+-----+-----+
| 123 | abc | 10 |
| 321 | zyx | 6 |
+-----+-----+-----+
知道如何进行这项工作吗?
【问题讨论】:
-
我正在使用这个查询来连接表这个查询是不确定的。例如 - 在第一个输出行中
t2.Re2有时可能是'abc',有时是'cba'..
标签: mysql