麻烦查询加入两个表

时间:2015-10-05 09:02:29

标签: mysql sql join where

我有两张桌子,我的第一张桌子是piutang

------------------------------------------------
id    nmr_bukti     tgl_transaksi   customer_id
------------------------------------------------
1     2015RSV0001   2015-09-17      42
2     2015RSV0002   2015-09-17      42
------------------------------------------------

和第二个表invoice_detail

------------------------------------------------
id    invoice_id     customer_id      nmr_bukti
------------------------------------------------
1     1              42               2015RSV0001       
2     1              42               2015RSV0001       
------------------------------------------------

我希望得到条件为customer_id = 42

的结果
------------------------------------------------
id    nmr_bukti     tgl_transaksi customer_id      
------------------------------------------------
1     2015RSV0002   2015-09-17            42               
------------------------------------------------

如何查询此案例?

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询 -

SELECT DISTINCT p.id, p.tgl_transaksi, p.customer_id 
FROM piutang AS p 
LEFT JOIN invoice_detail AS id 
ON p.customer_id=id.customer_id 
AND p.nmr_bukti=id.nmr_bukti 
WHERE p.customer_id = 42
AND id.id is null;

注意:为了获得更好的性能,应将customer_id和mnr_bukti字段编入索引。

答案 1 :(得分:0)

尝试 -

SELECT * FROM piutang
WHERE nmr_bukti NOT IN
    (SELECT DISTINCT nmr_bukti
    FROM invoice_detail
    WHERE customer_id = 42)
AND customer_id = 42;