左连接的Mysql查询问题

时间:2017-03-20 10:14:16

标签: php mysql group-by left-join inner-join

以下是我的询问:

SELECT 
    u.id, 
    CONCAT(u.FirstName, ' ', u.LastName) as customer, 
    u.MobileNumber, 
    u.EmailId, 
    (
        pmt.TotalCreditedAmt - trns.TotalDeductAmt
    ) as available_balance, 
    DATE_FORMAT(i.InvoiceDate, '%Y/%m/%d') as InvoiceDate, 
    pmt.TotalCreditedAmt, 
    trns.TotalDeductAmt 
FROM 
    (`Users` as u) 
    INNER JOIN (
        SELECT 
            Max(InvoiceDate) AS InvoiceDate, 
            Customer_id 
        FROM 
            Invoice 
        GROUP BY 
            Customer_id
    ) as i ON `i`.`Customer_id` = `u`.`Id` 
    LEFT JOIN (
        SELECT 
            sum(CreditedAmount) AS TotalCreditedAmt, 
            UserId 
        FROM 
            Payment 
        where 
            PaymentSucc = "Yes" 
        GROUP BY 
            UserId
    ) as pmt ON `pmt`.`UserId` = `u`.`id` 
    LEFT JOIN (
        SELECT 
            sum(Amount) AS TotalDeductAmt, 
            UserId 
        FROM 
            Transaction 
        GROUP BY 
            UserId
    ) as trns ON `trns`.`UserId` = `u`.`id` 
WHERE 
    `u`.`UserType` = 'User' 
    AND `pmt`.`TotalCreditedAmt` - trns.TotalDeductAmt < '0' 
ORDER BY 
    `u`.`EmailId` desc 

我在一个案例中遇到如下问题:

来自此用户ID的用户ID(1,2,3,4)的用户ID(1,2,3,4,5,6,7)已完成付款和用户ID(5, 6,7)尚未付款。因此用户ID(5,6,7)的输入不在付款表中。

和用户ID(1,2,3,4,5,6,7)已完成交易,其条目存在于交易表中。还会生成发票。

从上面的查询我只得到用户ID(1,2,3,4)的记录,因为它的条目存在于支付表中。 我还想要支付表中没有条目的记录。 请任何人帮我解决我的问题?

2 个答案:

答案 0 :(得分:0)

如果在与左连接表相关的where子句中添加条件,则获得内连接

 WHERE 
`u`.`UserType` = 'User' 
AND `pmt`.`TotalCreditedAmt` - trns.TotalDeductAmt < '0' //this should be place in on clause  

例如:

  ) as trns ON `trns`.`UserId` = `u`.`id`  
       and  `pmt`.`TotalCreditedAmt` - trns.TotalDeductAmt < '0' 
 WHERE  `u`.`UserType` = 'User' 

答案 1 :(得分:0)

如果我正确理解您的问题,您需要将此查询用于pmt。我们的想法是为付款表中没有的用户返回0

单独运行此查询并检查您是否正确获取TotalCreditedAmt。稍后您可以将其插入主查询。

(
SELECT 
    sum(case when p.userid is null then 0 else p.CreditedAmount) AS TotalCreditedAmt, 
    u.Id 
FROM 
    Users u left join Payment p on p.Userid=u.id
where 
    p.PaymentSucc = "Yes" 
GROUP BY 
    u.Id
)