使用加入还是子查询?

时间:2014-04-23 08:49:18

标签: mysql sql

我有3个表:StudentAddressStudentAddress

Student存储所有学生,地址存储所有地址详细信息,StudentAddress解决StudentAddress之间的多对多关系。此表存储了居住在多个地址的学生的详细信息。

我正在尝试列出已更改地址超过5次的学生的姓名和地址详情。

SELECT a.StudentID, CONCAT(b.FirstName + " " + b.LastName), c.MajorMunicipality,
       COUNT(a.AddressID) AS count 
FROM StudentAddress a 
INNER JOIN Member b 
        ON a.StudentID = b.StudentID 
INNER JOIN Address c 
        ON a.AddressID = b.AddressID
GROUP BY a.StudentID, a.AddressID 
HAVING count > 5;

此查询存在加入问题。请帮忙!!

3 个答案:

答案 0 :(得分:1)

我更喜欢join,因为它为您的第二次查询提供了更多使用结果的可能性。

为了帮助您缩小实际结果集,请尝试以下方法:

select a.MemberID
,      a.AddressID
,      COUNT(a.AddressID) as countAddress
from   MemberAddress a
group
by     a.MemberID
,      a.AddressID
having countAddress > 3
;

编辑:

试试这个:

select a.memberid
,      concat(b.firstname + " " + b.lastname)
,      c.majormunicipality
,      count(a.addressid) as countAddresses
from   memberaddress a 
join   member b 
on     a.memberid = b.memberid 
join   address c 
on     a.addressid = b.addressid
group
by     a.memberid
,      concat(b.firstname + " " + b.lastname)
,      c.majormunicipality
having count > 5
;

答案 1 :(得分:0)

过滤它们:

select a.MemberID,a.AddressID,COUNT(a.AddressID) as count 
from MemberAddress a group by a.MemberID HAVING COUNT(a.AddressID) > 3

答案 2 :(得分:0)

可能你应该使用HAVING Clause

      SELECT a.MemberID,
      a.AddressID,
      COUNT(a.AddressID) AS COUNT
      FROM MemberAddress a
      GROUP BY a.MemberID;
      HAVING COUNT >=3