MYSQL QUERY - 仅返回第一条记录

时间:2014-08-31 18:51:59

标签: mysql

我正在使用这个mysql查询。这里md.designation =“地区主席”等于许多记录,但返回的数据是与其相关的第一个记录中的每一个。确切地说,共有5个“地区主席”和48个俱乐部。我想返回所有俱乐部的数据,区域主席对相关俱乐部重复。

SELECT m.member_name name,md.designation, cd.club_name club, 
m.mobile mobile,cd.dues dues FROM member m,club_dues cd, 
member_designation md,member_repeat_designation mrd 
where md.designation ="Region Chairperson"  and cd.id =m.club_name 
and mrd.designation = md.id and mrd.parent_id = m.id

我无法弄清楚我做错了什么。如果不清楚,我会在这里或在必要时在sqlfiddle添加数据。

2 个答案:

答案 0 :(得分:0)

您的查询相当于:

SELECT      m.member_name name,
            md.designation, 
            cd.club_name club, 
            m.mobile mobile,
            cd.dues dues 

FROM        member m

INNER JOIN  club_dues cd
    ON      cd.id =m.club_name 

INNER JOIN  member_repeat_designation mrd 
    ON      mrd.parent_id = m.id

INNER JOIN  member_designation md
    ON      mrd.designation = md.id 
    AND     md.designation = "Region Chairperson"  

所以,只会带回“地区主席”的俱乐部,以及该俱乐部每个地区主席的一排。

要始终为每个俱乐部带回一行,您需要使用LEFT JOIN,例如:

SELECT      m.member_name name,
            md.designation, 
            cd.club_name club, 
            m.mobile mobile,
            cd.dues dues 

FROM        member m

LEFT JOIN  club_dues cd 
    ON      cd.id =m.club_name 

LEFT JOIN  member_repeat_designation mrd 
    ON      mrd.parent_id = m.id

LEFT JOIN   member_designation md
    ON      mrd.designation = md.id 
    AND     md.designation = "Region Chairperson"  

现在,这会为每个成员带回一行,不论其名称如何, close 到你想要的,但不够接近。

更接近的是添加一个DISTINCT子句,只返回具有唯一列组合的行,所以:

SELECT DISTINCT
            m.member_name name,
            md.designation, 
            cd.club_name club, 
            m.mobile mobile,
            cd.dues dues 

FROM        member m

LEFT JOIN  club_dues cd 
    ON      cd.id =m.club_name 

LEFT JOIN  member_repeat_designation mrd 
    ON      mrd.parent_id = m.id

LEFT JOIN   member_designation md
    ON      mrd.designation = md.id 
    AND     md.designation = "Region Chairperson"  

答案 1 :(得分:0)

尝试此查询:

SELECT cd.club_name club,m.member_name name,md.designation,  
m.mobile mobile,cd.dues dues 
FROM member m inner join club_dues cd on cd.id =m.club_name inner join    
member_designation   md on mrd.designation = md.id inner join 
member_repeat_designation mrd on mrd.parent_id = m.id
where md.designation LIKE 'Region Chairperson'  
group by cd.club_name;