连接多个列相同的表

时间:2015-08-11 16:24:56

标签: mysql join multiple-columns

我正在尝试计算我们的技术人员使用的产品数量

表格设置为

count1,size1,count2,size 2

$sql="select SUM(count1) AS count1, size1, SUM(count2) AS count2, size2 FROM PARTS WHERE crew='$crew' GROUP BY size1 ORDER BY size1 DESC";

可以工作,但显示为两个单独的列,我必须手动将两者一起添加。我试过的时候:

$sql="select SUM(count1) AS count1, size1, SUM(count2) AS count1, size2 AS size1 FROM PARTS WHERE crew='$crew' GROUP BY size1 ORDER BY size1 DESC";

我收到错误:组声明中的列'size1'不明确。我该怎么办?

2 个答案:

答案 0 :(得分:0)

这是你的意思吗?

$sql="select SUM(count1 + count2) AS count, size1 FROM PARTS WHERE crew='$crew' GROUP BY size1 ORDER BY size1 DESC";

答案 1 :(得分:0)

假设两个大小的列都是可互换的,您可以将每个零件大小的所有两个查询合并,然后应用sum计算:

SELECT   size, SUM(cnt)
FROM     (SELECT size1 AS size, count1 AS cnt FROM parts WHERE crew='$crew'
          UNION ALL
          SELECT size2 AS size, count2 AS cnt FROM parts WHERE crew='$crew') t
GROUP BY size
ORDER BY size DESC