简体   繁体   中英

Select all columns from two tables grouping by all columns in table1 and specific column in table2

My table structure is like below

    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

I need to query for select all from TblMemberInfo,TblCarInfo where Count(MemberId)=1

      MemberId    Name        CarNumber
        1        Sandeep        1111
        3        John           4859

Here is one method:

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;

This works, because with only one row in the group, the min() returns the right value.

And alternative approach uses 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
                 );

A couple more options!

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)

Using a subquery to retrieve the single MemberId's is a good idea if you have a lot of other columns you need to bring in as well

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
)

What would you do given that task? Probably: Find unique TblCarInfo member entries first and then look up the member name. So tell the DBMS to do exactly that:

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;

Or the same approach, but with a subquery in the select clause instead of a join:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM