[英]SQL query to join two tables despite the other table may not have values
[英]Select and join from two different tables based on multiple dynamic values that may be or may not be present in the other table
我有两个表,其中ID字段可能匹配,也可能不匹配,我想合并两个表。 我最好的尝试并没有返回所有缺失的值。
SELECT *
FROM (
SELECT matricula,SUM(monto) as 'pagosTotales' FROM referenciasdepago WHERE matricula IN('PM0000','PM0001') GROUP BY matricula
) AS A
INNER JOIN (
SELECT matricula, SUM(anual) as 'importeTotal' FROM documentos WHERE matricula IN ('PM0000','PM0001') GROUP BY matricula
) AS B ON A.matricula=B.matricula;
在“ WHERE matricula IN”之后,实际上可能包含50个以上的不同值。
这是我不想要的结果:
+-----------+--------------+-----------+--------------+
| matricula | pagosTotales | matricula | importeTotal |
+-----------+--------------+-----------+--------------+
| PM0000 | 1485 | PM0000 | 16030 |
+-----------+--------------+-----------+--------------+
这是另一个不希望的结果:
+-----------+--------------+-----------+--------------+
| matricula | pagosTotales | matricula | importeTotal |
+-----------+--------------+-----------+--------------+
| PM0000 | 1485 | PM0000 | 16030 |
| PM0000 | 1485 | PM0001 | 50 |
+-----------+--------------+-----------+--------------+
因为缺少表A中存在的PM0001。
代替内部联接,请尝试“完全外部联接”-如果存在则将返回匹配,如果不存在则仅返回来自A或B的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.