簡體   English   中英

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

[英]Using column from outer MySQL query in subquery

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

我知道我可能必須執行某種子查詢,但是我不確定如何引用子查詢中要查找的類別。 我確定這里缺少一些簡單的東西。 有人可以幫忙嗎? 謝謝!

在這里,您可以簡單地放下UNION並改用:

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

請注意SUM(布爾條件)模式。 這是一個非常有用的技巧,值得記住,因為它有一些漂亮的性能用法。 請注意,您可以在其中使用任何布爾條件,它只會為您提供滿足條件的組中的行數。

而不是您的查詢...您可能想要做類似的事情

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM