2011-06-30 26 views
0

我有不同的MySQL SELECT查詢,全部使用不同的where語句。這些產生總數,唯一總數,某種類型的總數。MySQL:使用多個where子句創建數據集

所以對於實例:

Loc | total | unique | missing 

London | 10 | 5 | 2 

New York |20 |10 |5 

目前我正在這些選擇查詢的分別,但我寧願一次運行它們。有沒有辦法在MySQL中做到這一點?

喜歡的東西:

SELECT 
    Location 
    Count(total) 
    SELECT 
     count(unique) 
    FROM 
     .. my tables.. 
    WHERE 
     .. where clause for unique part .. 
    GROUP BY 
     unique 
FROM 
    .. my tables .. 
WHERE 
    .. where clause for total part .. 
GROUP BY 
    total 
+0

後要合併這兩個查詢 - 因爲這一問題是抽象的僞SQL沒用那麼多沒有什麼從蒐集它。 –

+0

您示例的難點在於SQL不允許在SQL語句中用變量表示表名。爲此,你進入了存儲過程或腳本邏輯的範疇。 – dkretz

回答

0

謝謝大家。對於任何人試圖獲得與此交手,我最終的解決辦法是:

SELECT 
    Geo, 
    total, 
    SUM(unique) as unique 
FROM 
    (SELECT 
     Geo, 
     COUNT(total) AS total, 
     0 unique, 
    FROM 
     -- my tables -- 
    WHERE 
     -- where clause for totals -- 
    GROUP BY 
     Geo) 
    UNION 
    (SELECT 
     Geo, 
     0 total, 
     COUNT(unique) AS unique, 
    FROM 
     -- my tables -- 
    WHERE 
     -- where clause for unique -- 
    GROUP BY 
     Geo) 
) as tmptable 
GROUP BY 
    Geo 
2

也許你想要的是一個UNION

SELECT * from table where... 
UNION 
SELECT * from table where... 

顯然,列從每個查詢返回的必須是相同的。

+0

啊,有問題,最初的查詢沒有其他人擁有的列。我可以爲不包含它們的初始表做些'錯過= 0'嗎? – Hadleigh

+0

是的,'select null,x從table1 union選擇y,z from table2'是完全可以接受的。只要行計數在所有查詢中匹配,就可以進行聯合。 –

+0

它們不需要相同的列名,但它們需要相同的字段集(數字和類型)以相同的順序排列 - 如果需要,可以在這些位置使用NULL或值。 – dkretz

0

我期望子查詢(或幾個)是有序的。

select location, (select count(total) 
        from totalTable 
        where totalTable.location = locationTable.location) as total, 
       (select count(uniqe) 
        from uniqeTable 
        where uniqeTable.location = locationTable.location) as uniqe, 
       (select count(missing) 
        from missingTable 
        where missingTable.location = locationTable.location) as missing 
from locationTable 
where locationCriteria = searchCriteria 

您可以參考同一個表中的多個子查詢,如果需要的話 - 只是嘗試加入他們的ID,preferrably的東西是正確索引。顯然,where子句必須根據需要進行調整。