正确加入多个表

时间:2013-11-24 22:57:23

标签: mysql sql

我想显示payment_type 点数的所有付款。但是,我只看到一个而我的total列绝对不对。我必须搞砸JOINs,但我不知道如何解决它们。我尝试了LEFTs RIGHTs等不同的组合,并且不断出现。

我应该看到TammyTerry。总数目前是正确的。

这是fiddle of my SQL

另外,我在这里查询:

SELECT p.conf, 
       Concat(g.fname, ' ', g.lname) AS guest, 
       u.unit_name, 
       p.card_type, 
       p.payment_amt, 
       Sum(p.payment_amt)            AS total 
FROM   payments p, 
       guests g, 
       units u, 
       reservations r 
WHERE  p.reservation = r.id 
       AND r.guest = g.id 
       AND r.unit = u.id 
       AND p.payment_date = '2013-11-01' 
       AND p.payment_type = 'credit' 

2 个答案:

答案 0 :(得分:7)

你可以用子查询做到这一点:

SELECT p.conf, 
       Concat(g.fname, ' ', g.lname) AS guest, 
       u.unit_name, 
       p.card_type, 
       p.payment_amt,
       ( SELECT SUM(payment_amt) 
         FROM payments 
         WHERE payment_date = p.payment_date 
           AND payment_type = p.payment_type) AS total
FROM payments p 
LEFT JOIN reservations r ON p.reservation = r.id 
LEFT JOIN guests g ON r.guest = g.id 
LEFT JOIN units u ON  r.unit = u.id 
WHERE p.payment_date = '2013-11-01' 
  AND p.payment_type = 'credit'

Fiddle

或者你可以计算之后的总数,并将UNION计算到结果的其余部分:

UNION ALL
SELECT NULL, 'Total', NULL, NULL, SUM(payment_amt) 
FROM payments 
WHERE payment_date = '2013-11-01' 
  AND payment_type = 'credit'

Fiddle上的完整SQL

答案 1 :(得分:1)

您需要像这样添加GROUP BY:

GROUP BY g.fname, g.lname

请参阅Fiddle Demo