在子查询中使用外部MySQL查询中的列

时间:2012-06-20 19:36:30

标签: mysql subquery union

我有一个MySQL查询,我想稍微优化一下。这是:

SELECT `items`.category AS 'Category', 'Without' AS 'Which', COUNT(*) AS 'Count'
FROM `items` 
WHERE `id`=706 
GROUP BY `category`

UNION

SELECT `items`.category AS 'Category', 'With' AS 'Which', COUNT(*) AS 'Count'  
FROM `items` 
WHERE `id`=706 AND `qa_items`.pointsoff=0 
GROUP BY `category`;

我得到的是:

+---------------------------+---------+-------+
| Category                  | Which   | Count |
+---------------------------+---------+-------+
| Category A                | Without |     3 |
| Category B                | Without |     8 |
| Category C                | Without |     4 |
| Category A                | With    |     2 |
| Category B                | With    |     6 |
| Category C                | With    |     4 |
+---------------------------+---------+-------+

但我想要的是:

+---------------------------+---------+-------+
| Category                  | Without | With  |
+---------------------------+---------+-------+
| Category A                |       3 |     2 |
| Category B                |       8 |     6 |
| Category C                |       4 |     4 |
+---------------------------+---------+-------+

我知道我可能不得不做某种子查询,但我不确定如何在子查询中引用我要查找的类别。我确信这里有一些简单的东西我很想念。有人可以帮忙吗?谢谢!

2 个答案:

答案 0 :(得分:1)

在这里你可以简单地删除UNION并改为使用:

SELECT
    category as Category,
    COUNT(*) as Without,
    SUM(pointsoff = 0) as With
FROM items
WHERE id=706
GROUP BY category;

注意SUM(布尔条件)模式。这是一个值得记住的真正有用的技巧,因为它具有一些漂亮的性能用法。请注意,您可以使用所需的任何布尔条件,并且它只会为您提供满足条件的组中的行数。

答案 1 :(得分:0)

而不是你的查询...你会想要做类似

的事情
SUM(IF(items.Without, 1,0)) as Without, SUM(IF(items.With, 1,0)) as With for the columns