选择table1中所有列和table2中特定列分组的两个表中的所有列

时间:2016-05-11 02:38:44

标签: sql sql-server

我的表结构如下所示

    TblMemberInfo          |         TblCarInfo
 MemberID   Name           |         Id     MemberId     CarNumber
    1       Sandeep        |         1         2            1234
    2       Vishal         |         2         1            1111
    3       John           |         3         4            2458
    4       Kevin          |         4         2            1296
    5       Devid          |         5         4            7878
                           |         6         3            4859

我需要从TblMemberInfo查询select all,TblCarInfo其中Count(MemberId)= 1

      MemberId    Name        CarNumber
        1        Sandeep        1111
        3        John           4859

3 个答案:

答案 0 :(得分:3)

这是一种方法:

select mi.MemberID, mi.Name, min(CarNumber) as CarNumber
from TblMemberInfo mi join
     TblCarInfo ci
     on mi.MemberID = ci.MemberID
group by mi.MemberID, mi.Name
having count(*) = 1;

这样可行,因为组中只有一行,min()会返回正确的值。

替代方法使用not exists

select mi.MemberID, mi.Name, ci.CarNumber
from TblMemberInfo mi join
     TblCarInfo ci
     on mi.MemberID = ci.MemberID
where not exists (select 1
                  from TblCarInfo ci2
                  where ci2.MemberID = ci.MemberID and ci2.id <> ci.id
                 );

答案 1 :(得分:1)

还有更多选择!

select mi.MemberId, mi.Name, ci.CarNumber
from TblMemberInfo mi 
join TblCarInfo ci on 
   mi.MemberId = ci.MemberId
group by mi.MemberId, mi.Name, ci.CarNumber
having min(ci.Id) = max(ci.Id)

如果您还需要引入许多其他列,则使用子查询检索单个MemberId's是个好主意

select mi.MemberId, mi.Name, ci.CarNumber
from TblMemberInfo mi   
join TblCarInfo ci on 
   mi.MemberId = ci.MemberId
where mi.MemberId in
(
   select MemberId     
   from TblCarInfo 
   group by MemberId
   having count(*) = 1
)

答案 2 :(得分:1)

做了什么?可能:首先查找唯一的TblCarInfo成员条目,然后查找成员名称。所以告诉DBMS要做到这一点:

select m.memberid, m.name, c.carnumber
from
(
  select memberid, min(carnumber) as carnumber
  from tblcarinfo
  group by memberid
  having count(*) = 1
) c
join tblmemberinfo m on m.memberid = c.memberid;

或者采用相同的方法,但在select子句中使用子查询而不是连接:

select
  c.memberid, 
  (select m.name from tblmemberinfo m where m.memberid = c.memberid) as name,
  c.carnumber
from
(
  select memberid, min(carnumber) as carnumber
  from tblcarinfo
  group by memberid
  having count(*) = 1
) c;