2014-05-06 32 views
0

我有兩個不同的表,我想從中提取唯一ID的數目。每個單表查詢如下所示MySQL UNION - 將兩個單值查詢輸出到不同的列中

SELECT COUNT(DISTINCT(`uniqueid`)) as `t1ID` FROM `table1` 

SELECT COUNT(DISTINCT(`uniqueid`)) as `t2ID` FROM `table2` WHERE `condition`='true' 

我想這兩個查詢合併成一個單一的語句。我知道我可以使用數名從第一查詢作爲列名使用

SELECT COUNT(DISTINCT(`uniqueid`)) as `t1ID` FROM `table1` 
UNION ALL 
SELECT COUNT(DISTINCT(`uniqueid`)) as `t2ID` FROM `table2` WHERE `condition`='true' 

然而,這個輸出是兩個數值分成兩行顯示:

+------+ 
+ t1ID + 
+------+ 
+ 4 + 
+------+ 
+ 5 + 
+------+ 

有沒有辦法讓UNION查詢以相應的計數名稱輸出兩列中的數據?即

+------+------+ 
+ t1ID + t2ID + 
+------+------+ 
+ 4 + 5 + 
+------+------+ 

這樣,這將是一個更容易直接引用的結果,而不是起伏記得在查詢提交的順序。

回答

1
SELECT (SELECT COUNT(DISTINCT(`uniqueid`)) FROM `table1`) as `t1ID`, 
(SELECT COUNT(DISTINCT(`uniqueid`)) FROM `table2` WHERE `condition`='true') as `t2ID` 
+0

D'oh!太簡單! * facepalm * – Tomm

+0

謝謝堆,隊友。 – Tomm

+0

沒問題... :) – PeterRing

0
select sub1.t1ID, sub2.t2ID 
from (SELECT uniqueid, COUNT(DISTINCT(`uniqueid`)) as `t1ID` FROM `table1`) sub1 
join (SELECT uniqueid, COUNT(DISTINCT(`uniqueid`)) as `t2ID` FROM `table2` 
     WHERE `condition`='true') sub2 on sub1.uniqueid=sub2.uniqueid 
0

試試這個

select sum(t1ID) as t1ID 
    , sum(t2ID) as t2ID 
from (
    SELECT COUNT(DISTINCT(`uniqueid`)) as `t1ID`, 0 as `t2ID` FROM `table1` 
    union all 
    SELECT 0 as `t1ID`, COUNT(DISTINCT(`uniqueid`)) as `t2ID` FROM `table2` 
    WHERE `condition`='true' 
) 
0
select sum(t1ID) as t1ID , sum(t2ID) as t2ID 
(
    SELECT COUNT(DISTINCT(`uniqueid`)) as `t1ID`, 0 as `t2ID` FROM `table1` 
    UNION ALL 
    SELECT 0 as `t1ID` , COUNT(DISTINCT(`uniqueid`)) as `t2ID` FROM `table2` WHERE `condition`='true' 
)t 

確保將派生表的別名,因爲我有t否則你會得到錯誤的

Every derived table must have its own alias 
0

如果我猜的,你想識別輸出,並知道哪個VA泰倫從哪個表...

一個好的技巧是這個

SELECT COUNT(DISTINCT(`uniqueid`)) as `t1ID`, 't1ID' as 'X' FROM `table1` 
UNION ALL 
SELECT COUNT(DISTINCT(`uniqueid`)) as `t2ID`, 't2ID' as 'X' FROM `table2` WHERE `condition`='true' 

增加,「t1ID」和「T2ID」將出現接近計 值和讀取行時,得到第二值(按名稱X),那麼你可以知道哪個值來自哪個來源。

相關問題