使用单个查询加入三个表

时间:2015-04-11 05:21:16

标签: mysql sql sql-server left-join

我有三张桌子,我想加入他们。

加入两个表可以很好地工作,但连接三个表只返回一行

表名

  • 为userDetails
  • saletrack
  • paymentDetails

查询#1:

SELECT  
    `userdetails`.CustomerIndex, 
    `userdetails`.FristName,
    SUM(`paymentdetails`.Amountofpaying) TotalPaid
FROM
    `userdetails`
LEFT JOIN 
    `paymentdetails` ON `userdetails`.CustomerIndex=`paymentdetails` .CustomerID
GROUP BY 
    `userdetails`.CustomerIndex,`userdetails`.FristName

查询#2:

SELECT  
    `userdetails`.CustomerIndex, 
    `userdetails`.FristName,
    SUM(`saletrack`.Total) Totalbilled
FROM 
    `userdetails`
LEFT JOIN 
    `saletrack` ON `userdetails`.CustomerIndex = `saletrack`.CustomerId
GROUP BY 
    `userdetails`.CustomerIndex, `userdetails`.FristName

查询#3:

SELECT 
    s.CustomerId, 
    SUM(s.Total) Totalbilled, 
    p.CustomerID, 
    SUM(p.Amountofpaying) TotalPaid
FROM  
    `userdetails` AS ud
LEFT JOIN 
    `saletrack` AS s ON ud.CustomerIndex = s.CustomerId
LEFT JOIN 
    `paymentdetails` AS p ON ud.CustomerIndex = p.CustomerID
WHERE 
    p.CustomerID = ud.CustomerIndex
    AND s.CustomerId = ud.CustomerIndex
LIMIT 0 , 30

2 个答案:

答案 0 :(得分:1)

正如你所提到的 ud.CustomerIndex = s.CustomerId&& ud.CustomerIndex = p.CustomerID 在连接中然后无需再次放入where条件。试试这个:

SELECT s.CustomerId, SUM( s.Total ) Totalbilled, p.CustomerID, SUM( p.Amountofpaying ) TotalPaid
FROM  `userdetails` AS ud
LEFT JOIN  `saletrack` AS s ON ud.CustomerIndex = s.CustomerId
LEFT JOIN  `paymentdetails` AS p ON ud.CustomerIndex = p.CustomerID
LIMIT 0 , 30

答案 1 :(得分:0)

我们需要按查询分组

SELECT s.CustomerId, SUM( s.Total ) Totalbilled, p.CustomerID, SUM( p.Amountofpaying ) TotalPaid
FROM  `userdetails` AS ud
LEFT JOIN  `saletrack` AS s ON ud.CustomerIndex = s.CustomerId
LEFT JOIN  `paymentdetails` AS p ON ud.CustomerIndex = p.CustomerID
WHERE p.CustomerID = ud.CustomerIndex
AND s.CustomerId = ud.CustomerIndex
***GROUP BY ud.CustomerIndex, ud.FristName***
LIMIT 0 , 30