2013-08-16 152 views
1

我想從我的MySQL表中獲取一些統計信息,並希望將它保留爲單個查詢。只是不知道如何(或者甚至可能)。我有兩個疑問:將同一表中的查詢合併爲一個查詢

SELECT COUNT(*) AS `accept` 
FROM `status` 
WHERE `groupID` IN (98779,98780) 
    AND `group` = 'order' 
    AND `status` = 'accept' 

SELECT COUNT(*) AS `price` 
FROM `status` 
WHERE `groupID` IN (98779, 98780) 
    AND `group` = 'quotation' 
    AND (`status` = 'final' OR `status` = 'manualprice') 

我最好的建議是,他們在一個單一的SELECT這樣的組合:

SELECT 
    (SELECT COUNT(*) AS `accept` 
    FROM `status` 
    WHERE `groupID` IN (98779, 98780) AND `group` = 'order' AND `status` = 'accept') AS accept, 
    (SELECT COUNT(*) AS `price` 
    FROM `status` 
    WHERE `groupID` IN (98779, 98780) AND `group` = 'quotation' AND (`status` = 'final' OR `status` = 'manualprice')) AS price 

有沒有更好的辦法?

回答

0
SELECT 
    sum(if(`group` = 'order' AND `status` = 'accept', 1,0)) as `accept`, 
    sum(if(`group` = 'quotation' AND (`status` = 'final' OR `status` = 'manualprice'), 1,0)) as `price` 
FROM 
    `status` 
WHERE 
    `groupID` IN (98779,98780) 
    AND `group` IN ('order', 'quotation') 
    AND `status` IN ('accept', 'final', 'manualprice') 

編輯這是基本相同,對方的回答通過491243.我已經使用一個額外的if語句,貌似是不是必需的。

+0

這是非常聰明的......這麼好有更多的學習。我能夠將我的查詢優化10倍。非常感謝! –

1

這裏是另一種方式來做到這一點,

SELECT SUM(`group` = 'order' AND `status` = 'accept') AS `ACCEPT`, 
     SUM(`group` = 'quotation' AND (`status` = 'final' OR `status` = 'manualprice')) AS `PRICE` 
FROM `status` 
WHERE `groupID` IN (98779, 98780) AND 
     `group` IN ('order', 'quotation') AND 
     `status` IN ('accept', 'final', 'manualprice')