2015-10-05 16 views
-1

我有兩個表,我的第一個表是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    
------------------------------------------------ 

我該如何查詢這種情況?

+0

兩個你的表有ID = 1 nmr_bukti = '2015RSV0001' ..那麼,爲什麼nmr_bukti = '2015RSV0002' 爲ID = 1在你想要的結果? –

+0

想要的結果中有哪個id列,來自piutang的還是來自invoice_detail的? – jarlh

+0

我開始認爲沒有它們不是這兩個,id實際上是一個row_number :) –

回答

0

您可以使用下面的query

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應該被索引。

0

嘗試 -

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

與SELECT * FROM工作piutang WHERE nmr_bukti NOT IN (SELECT DISTINCT nmr_bukti FROM invoice_detail WHERE CUSTOMER_ID = 42) AND CUSTOMER_ID = 42; thxs guys – user3585448

+0

不客氣。 – toonice

+0

爲什麼在子選擇DISTINCT?如果nmr_bukti不可用,那麼NOT IN有點「危險」......) – jarlh