尝试将两个分组查询合并为一个

时间:2018-02-09 21:59:58

标签: php mysql sql select join

我试图获取与帐户关联的所有点击次数和销售额的列表,其中两个表都将帐户ID作为索引。现在我有:

SELECT ACCOUNT, SUM(REVENUE) AS R, COUNT(*) AS SALES
FROM CONVERSIONS
WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT

SELECT ACCOUNT, COUNT(DISTINCT BIN_IP) AS CLICKS
FROM CLICKS
WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT

这给了我两个列表,但是我必须做大量的数组操作才能让它们排成一行。试着看看是否有办法加入这两个查询,但迄今为止我所尝试的一切都失败了。

编辑:为了清楚起见,我在尝试过的每次加入时遇到的问题是我失去了销售,没有点击,点击和销售的情况。加入它们并检查table.ACCOUNT = table2.ACCOUNT仅在有点击次数和销售额时才有效。这基本上是我挣扎的难题的一部分。

2 个答案:

答案 0 :(得分:1)

如果您对所拥有的查询感到满意,可以使用:

SELECT conv.ACCOUNT, conv.R, conv.SALES, clicks.CLICKS
FROM
(SELECT ACCOUNT, SUM(REVENUE) AS R, COUNT(*) AS SALES
 FROM CONVERSIONS
 WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT) conv
LEFT JOIN
(SELECT ACCOUNT, COUNT(DISTINCT BIN_IP) AS CLICKS
 FROM CLICKS
 WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT) clicks
ON conv.ACCOUNT = clicks.ACCOUNT
UNION
SELECT clicks2.ACCOUNT, conv2.R, conv2.SALES, clicks2.CLICKS
FROM
(SELECT ACCOUNT, COUNT(DISTINCT BIN_IP) AS CLICKS
 FROM CLICKS
 WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT) clicks2
LEFT JOIN
(SELECT ACCOUNT, SUM(REVENUE) AS R, COUNT(*) AS SALES
 FROM CONVERSIONS
 WHERE ACCOUNT = ? AND TIME BETWEEN ? AND ? GROUP BY ACCOUNT) conv2
ON clicks2.ACCOUNT = conv2.ACCOUNT

这很乱,因为mySQL没有完全加入。所以你必须使用两个左连接和UNION。请注意,第一组连接,转换和单击,将包括只有转换记录和两个表中都有记录的情况。第二组连接,conv2和clicks2,将返回仅有点击的情况。

答案 1 :(得分:0)

可能更容易将colums点击添加到第一个选择,列r和销售到第二个。(在选择中将这些设置为0)

然后,您可以按列帐户进行两个选择和分组的并集。您需要使用sum来表示销售额,点击次数和r列。

在此之后,你可以左边加入帐户表,结果是获得所有帐户(也包括没有点击和销售的帐户)