2016-12-13 212 views
0

我有一個表,稱爲用戶,其中有用戶和各自referralIds。一些用戶沒有referralIds並且是NULL。Mysql左連接不返回空值

我有第二個表稱爲交易其中sum(transactions.amount)會給我的客戶中產生,只要收益爲TRANSACTION_TYPE = 1個

問題:我在做一個左連接,將顯示我的收入根據referralId生成。我希望有一個小組能夠顯示我的收入來自沒有推薦項的用戶。然而,空referralId被返回NULL收入以及

SELECT 
users.referralId, b.revenue 
FROM users 
     LEFT JOIN 
    (SELECT 
     users.referralId, SUM(transactions.amount) AS revenue 
    FROM 
     transactions 
    LEFT JOIN users ON users.username = transactions.username 
    WHERE 
     transaction_type = 1 and date(created_at) between @start_date and @end_date 
    GROUP BY users.referralId) b ON users.referralId = b.referralId 
group by referralId 

回答

0

在這種情況下考慮,而不是你的外部查詢做INNER JOIN。此外,沒有看到你爲什麼需要這個外部查詢的原因。你的內部子查詢應該能夠獲得所需的數據。

SELECT 
users.referralId, b.revenue 
FROM users 
     INNER JOIN 
    (SELECT 
     users.referralId, SUM(transactions.amount) AS revenue 
    FROM 
     transactions 
    LEFT JOIN users ON users.username = transactions.username 
    WHERE 
     transaction_type = 1 and date(created_at) between @start_date and @end_date 
    GROUP BY users.referralId) b ON users.referralId = b.referralId 
group by referralId 
0

LEFT OUTER JOIN爲我工作。你應該試試看