左连接查询将列保持为空

时间:2017-08-01 08:21:37

标签: mysql join

我有两个名为#include "plsqlHx.h" #include <iostream> #include <windows.h> #include <string> const char *const Desc = "C++Builder Plug-In demo 1"; int PlugInID; const char* IdentifyPlugIn(int ID){ PlugInID = ID; return Desc; } const char* CreateMenuItem(int Index){ switch (Index) { case 1 : return "Tools / &Plug-In 1 Demo..."; } return ""; } void OnMenuClick (int Index){ switch(Index){ case 11: cout << "Hello"; break; case 12: cout << "Goodbye"; break; } } PaymentMaster的表格以及两个由PaymentDetails列加入的表格。这是我的查询

receiptID

以下查询为我提供了此结果

enter image description here

请注意, SELECT pm.receiptID , pm.recievedAmount , pd.invono , pd.paidAmount FROM PaymentMaster pm LEFT JOIN PaymentDetail pd ON pd.receiptID = pm.receiptID 中有两条有关receiptID PaymentDetails的记录。这就是为PAY0002显示两个记录的原因。 (PAY0002)。

问题是,我不想在两行中打印INV0001,INV0002。如果id相同则列应该为空。最终结果应该是这样的

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用GROUP BY关键字对其进行分组,您的查询将变为类似

  SELECT pm.receiptID
      , pm.recievedAmount
      , pd.invono
      , pd.paidAmount 
 FROM PaymentMaster pm LEFT JOIN PaymentDetail pd ON pd.receiptID = pm.receiptID GROUP BY pd.receiptID

答案 1 :(得分:0)

您可以使用变量来控制显示的内容

drop table if exists pm,pd;
create table pm(id varchar(8), amt int);
create table pd(id varchar(8), amt int);

insert into pm values ('aaa',1000),('bbb','100');
insert into pd values ('aaa',100),('aaa',100),('bbb',100);


Select case when rn = 1 then pmid else '' end as pmid,
         case when rn = 1 then pmamt else '' end as pmamt,
         pdid,pdamt
from
(
select pm.id pmid,pm.amt pmamt,
        pd.id pdid, pd.amt pdamt
        ,if(pm.id<> @p, @rn:=1,@rn:=@rn+1) rn
        ,@p:=pm.id
from pm
join pd on pd.id = pm.id
,(select @rn:=0,@p:=0) rn
) s