我有一个名为users的表,它有用户和各自的referralIds。一些用户没有referralIds并且是NULL。
我有一个名为Transactions的第二个表,其中sum(transactions.amount)将为我提供客户生成的收入,只要transaction_type = 1
问题:我正在进行左连接,这将显示每个referralId产生的收入。我想要一个小组,它显示我没有推荐的用户产生的收入。但是,Null 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 :(得分: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
答案 1 :(得分:0)
LEFT OUTER JOIN为我工作。你应该试一试