MySQL避免使用来自不同表的GROUP BY列

时间:2015-03-03 05:03:05

标签: mysql group-by

我在以下查询中执行了来自不同表的2列的分组。我知道这会导致性能问题。我不确定如何优化这一点。非常感谢任何帮助!

查询

SELECT tableA.col AS tableAcol, 
       tableB.col AS tableBcol, 
       SUM(tableB.count) AS total
FROM tableB, tableA
WHERE tableB.uid = tableA.uid 
AND tableA.eid=? 
GROUP BY tableA.col, tableB.col

2 个答案:

答案 0 :(得分:0)

您可以使用执行部分和的子查询来减少外部查询中求和的JOIN的大小。

SELECT tableA.col AS tableAcol
       tableBgrouped.col AS tableBcol,
       SUM(tableBgrouped.count) AS total
FROM tableA
JOIN (SELECT uid, col, SUM(count) AS count
      FROM tableB
      GROUP BY uid, col) AS tableBgrouped
ON tableA.uid = tableBgrouped.uid
WHERE tableA.eid = ?
GROUP BY tableAcol, tableBcol

答案 1 :(得分:0)

SELECT A.`col` AS tableAcol
       B.`col` AS tableBcol,
       SUM(B.`count`) AS total
FROM tableA A
JOIN (SELECT B1.`uid`, B1.`col`, SUM(B1.`count`) AS count
      FROM tableB B
      GROUP BY B1.`uid`, B1.`col`) AS B
ON A.`uid` = B.`uid`
WHERE A.`eid` = ?
GROUP BY A.`col`, B.`col`