如何使用mysql从存储过程中删除重复项

时间:2016-04-15 10:53:47

标签: mysql sql stored-procedures left-join inner-join

请查看这些表格。

  • FAMILY表:FamilyID(pk),familyName
  • PARENT表:ParentID(pk),FamilyID(fk),userName,email,密码
  • KID表:KidID(pk),FamilyID(fk),用户名,电子邮件,密码

以下是从特定姓氏中获取父母和孩子的存储过程。这里从3个表中检索数据。

CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_Dashboard`(IN `inputuserName` VARCHAR(255))
BEGIN
SET @familyID = (SELECT familyID FROM PARENT WHERE userName = inputuserName); 

SELECT  
    F.familyName AS FamilyName, 
    P.userName AS Parents, 
    K.userName AS Kids 
FROM 
    PARENT P 
INNER JOIN 
    FAMILY F ON P.FamilyID = F.FamilyID 
LEFT OUTER JOIN 
    KID K ON K.FamilyID = F.FamilyID
WHERE 
   P.FamilyID = @familyID AND F.FamilyID = @familyID
GROUP BY 
    FamilyName, Parents,Kids;
END

输出应为

enter image description here

相反,它创建了家庭,父母和家庭的复制品。孩子们,给我6条记录。

1 个答案:

答案 0 :(得分:0)

You want to combine the two lists in columns. This is not a very "relational" thing to do. It is possible, but not using join. Instead, you can do this using aggregation:

select family_name, max(parent) as parent, max(kid) as kid
from ((select family_name, user_name as parent, NULL as kid
              (@rn := if(@f = family_name, @rn + 1,
                         if(@f := family_name, 1, 1)
                        )
               ) as rn
       from family f join
            parents p
            using (familyid) cross join
            (select @f := '', @rn := 0) params
       order by family_name
      ) union all
      (select family_name, NULL, k.user_name,
              (@rnk := if(@fk = family_name, @rnk + 1,
                         if(@fk := family_name, 1, 1)
                        )
               ) as rnk
       from family f join
            kids k
            using (familyid) cross join
            (select @fk := '', @rnk := 0) params
       order by family_name
      ) 
     ) pk
group by family_name, rn;