如何合并来自2个表的数据,包括不匹配的字段

时间:2015-12-16 21:27:39

标签: php mysql join

我有以下MySQL声明:

SELECT gls.id AS glid, gls.gl, gls.name AS gl_name, requests.costCenter, budgets.total as totalBudgeted,
                    ROUND(SUM(CASE WHEN requests.ap = 1 THEN totalCost ELSE 0 END), 2) AS ap1, 
                    ROUND(SUM(CASE WHEN requests.ap = 2 THEN totalCost ELSE 0 END), 2) AS ap2,
                    ROUND(SUM(CASE WHEN requests.ap = 3 THEN totalCost ELSE 0 END), 2) AS ap3,
                    ROUND(SUM(CASE WHEN requests.ap = 4 THEN totalCost ELSE 0 END), 2) AS ap4,
                    ROUND(SUM(CASE WHEN requests.ap = 5 THEN totalCost ELSE 0 END), 2) AS ap5,
                    ROUND(SUM(CASE WHEN requests.ap = 6 THEN totalCost ELSE 0 END), 2) AS ap6,
                    ROUND(SUM(CASE WHEN requests.ap = 7 THEN totalCost ELSE 0 END), 2) AS ap7,
                    ROUND(SUM(CASE WHEN requests.ap = 8 THEN totalCost ELSE 0 END), 2) AS ap8,
                    ROUND(SUM(CASE WHEN requests.ap = 9 THEN totalCost ELSE 0 END), 2) AS ap9,
                    ROUND(SUM(CASE WHEN requests.ap = 10 THEN totalCost ELSE 0 END), 2) AS ap10,
                    ROUND(SUM(CASE WHEN requests.ap = 11 THEN totalCost ELSE 0 END), 2) AS ap11,
                    ROUND(SUM(CASE WHEN requests.ap = 12 THEN totalCost ELSE 0 END), 2) AS ap12 
                FROM gls
                    LEFT JOIN requests ON requests.glid = gls.id 
                    LEFT JOIN budgets ON budgets.gl = gls.id AND budgets.costCenter = 2
                WHERE requests.status = 'approved' AND requests.costCenter = 2
                    GROUP BY gls.id

我的问题是,当我运行查询时,我只会得到与其相关的请求的" gl" s。 " gl" s不会在请求表中显示相应的条目。

我尝试了一些JOINS的排列,但似乎没有任何效果。对我来说很明显,限制因素是阻止所有GL显示的LEFT JOIN requests ON requests.glid = gls.id,但据我所知,LEFT JOIN应保留所有GL表值,并且只添加相应的REQUESTS值。

出于隐私原因,我无法显示任何数据,但我可以尝试总结一下:

在gls表中有30行,

在请求表中,可以有任意数量的行,但每个行都有一个外键将它们链接到gls表中的一行。基本上,我的查询应该给我一张所有gls的表格,并标记旁边相应请求的信息。

此外,我感觉有人在这里可以清理这个查询并使其更短,更短。

谢谢大家!

1 个答案:

答案 0 :(得分:0)

你对LEFT JOIN是正确的。问题是你的WHERE:

WHERE requests.status = 'approved' AND requests.costCenter = 2

这会过滤掉没有请求的所有行。

相反,您希望将该条件移至JOIN:

LEFT JOIN requests 
  ON requests.glid = gls.id 
 AND requests.status = 'approved' AND requests.costCenter = 2