2012-12-19 148 views
0

我想根據labour_master_id來自不同表格的兩個字段的總和。但是當我得到結果時,它顯示出不同的結果。來自兩個不同表格的兩個字段的Mysql總和

這裏是我試過

select labours.labour_master_id, 
    sum(labours.amount_paid), 
    sum(labour_cashcredits.amount_paid) 
FROM labours 
left join labour_cashcredits 
    on labours.labour_master_id=labour_cashcredits.labour_master_id 
group by labours.labour_master_id 

它可以被映射兩次,它顯示錯誤的結果。

現在問題正在發生總和。

任何想法如何做到這一點?

我有這個query..please幫助錯誤

select l.labour_master_id, l.amount_paid as payable, cc.amount_paid as paid 
       FROM 
       (
        select labour_master_id, sum(amount_paid) amount_paid 
        from labours 
        group by labour_master_id 
       ) l 
       left join 
       (
        select labour_master_id, sum(amount_paid) amount_paid 
        from labour_cashcredits 
        group by labour_master_id 
       ) cc 
           left join 
       (
        select name,id 
        from labour_masters 
       ) lm 
        on l.labour_master_id=cc.labour_master_id 
on l.labour_master_id=lm.labour_masters.id 
+0

?你可以給數據樣本嗎? –

+1

,因爲在第二個表可能數據退出或沒有 –

+0

總和,如果數據退出第二個表 –

回答

1

您可以嘗試使用子查詢來執行每個表中的總和:

select l.labour_master_id, 
    l.amount_paid, 
    cc.amount_paid 
FROM 
(
    select labour_master_id, sum(amount_paid) amount_paid 
    from labours 
    group by labour_master_id 
) l 
left join 
(
    select labour_master_id, sum(amount_paid) amount_paid 
    from labour_cashcredits 
    group by labour_master_id 
) cc 
    on l.labour_master_id=cc.labour_master_id 
+0

感謝它對我有用..是否有任何方法來做沒有子查詢? –

+0

@AmandeepKaur你可能會改變這種情況,只在第二張表上使用子查詢,但IMO有時候更容易使用子查詢。 – Taryn

+0

好的非常感謝:) –

0

使用this--

 SELECT labours.labour_master_id, SUM (labours.amount_paid), 
    SUM (labour_cashcredits.amount_paid) 
    FROM labours,labour_cashcredits 
    where labours.labour_master_id = labour_cashcredits.labour_master_id 
GROUP BY labours.labour_master_id 
0

希望這是你想要的,

select labours.labour_master_id, 
    sum(ifnull(labours.amount_paid,0))+ 
    sum(ifnull(labour_cashcredits.amount_paid),0) sum 
FROM labours 
left join labour_cashcredits 
    on labours.labour_master_id=labour_cashcredits.labour_master_id 
group by labours.labour_master_id 
0

嘗試使用子查詢第二SUM:你爲什麼要使用左連接這裏

SELECT labours.labour_master_id, SUM(labours.amount_paid), 
      (SELECT SUM(amount_paid) FROM labour_cashcredits 
      WHERE labour_master_id = labours.labour_master_id 
      GROUP BY labour_master_id 
      ) AS credit_amount_paid 
FROM labours 
LEFT JOIN labour_cashcredits ON labours.labour_master_id = labour_cashcredits.labour_master_id 
GROUP BY labours.labour_master_id 
相關問題