0

我有一个 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 |
+---------------------------+---------+-------+

我知道我可能必须做某种子查询,但我不确定如何引用我在子查询中寻找的类别。我确定这里缺少一些简单的东西。任何人都可以帮忙吗?谢谢!

4

2 回答 2

1

在这里,您可以简单地删除 UNION 并改用:

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

请注意 SUM(布尔条件)模式。这是一个非常有用的技巧,值得记住,因为它在性能方面有一些漂亮的用法。请注意,您可以在其中使用任何您想要的布尔条件,它只会为您提供组中满足条件的行数。

于 2012-06-20T20:39:39.170 回答
0

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

SUM(IF(items.Without, 1,0)) as Without, SUM(IF(items.With, 1,0)) as With for the columns 
于 2012-06-20T19:51:51.217 回答