2015-09-06 110 views
0
SELECT save AS 'Simpanan', owe AS 'Hutang' 
FROM 
(
SELECT t.amount AS save, NULL AS owe 
FROM trans t JOIN category cat 
ON t.category_id = cat.category_id 
WHERE cat.category_id = 1 
UNION ALL 
SELECT NULL AS save, t.amount AS owe 
FROM trans t JOIN category cat 
ON t.category_id = cat.category_id 
WHERE cat.category_id = 2 
) 

我一直在努力與此mysql查詢。我想實現的是,結果只有1排。目前這個查詢輸出2行,列中有一些字段爲NULL。我怎樣才能使它只輸出1行是這樣的:與JOIN表和合並結果到1行mysql多個查詢

Simpanan Hutang 
500   200 

到這裏看看:http://sqlfiddle.com/#!5/89973/30

回答

2

如果你肯定只有一個結果使用子查詢。

SELECT 
    (SELECT t.amount AS save 
    FROM trans t JOIN category cat 
    ON t.category_id = cat.category_id 
    WHERE cat.category_id = 1) AS 'Simpanan', 
    (SELECT t.amount AS owe 
    FROM trans t JOIN category cat 
    ON t.category_id = cat.category_id 
    WHERE cat.category_id = 2) AS 'Hutang' 

或者:

SELECT MAX(save) AS 'Simpanan', MAX(owe) AS 'Hutang' 
FROM 
(
SELECT t.amount AS save, NULL AS owe 
FROM trans t JOIN category cat 
ON t.category_id = cat.category_id 
WHERE cat.category_id = 1 
UNION ALL 
SELECT NULL AS save, t.amount AS owe 
FROM trans t JOIN category cat 
ON t.category_id = cat.category_id 
WHERE cat.category_id = 2 
) 
+0

謝謝,這是我努力實現,幾個小時前:) –

+0

感謝名單的第二個答案。我以爲我以前的查詢完全沒用。 'MAX' ftw! –