加入具有相同ID的多个记录的表

时间:2017-12-27 22:59:09

标签: mysql join

我有两张桌子:

applicant_personal_info看起来像这样:

A_id         FirstName        LastName
 1            Fahad            Subzwari

applicant_professional_info表看起来像这样:

A_id       JobOrganization    JobDuration     TotalExperience
 1             10Pearls          12 Months       20 Months
 1               Axact            8 Months       20 Months

我想从两个表中选择数据并尝试过此查询:

SELECT GROUP_CONCAT(aper.FirstName,aper.LastName) AS Name, 
apro.totalExperience '+
'FROM applicant_personal_info aper INNER JOIN applicant_professional_info 
 apro ON '+
 'aper.ApplicantID = apro.ApplicantID WHERE aper.ApplicantID =

但是这个查询返回Name 2次,因为applicant_professional_info表中有2条记录,如下所示:

 {
   Name : Fahad Subzwari, Fahad Subzwari,
   TotalExperience: 20 Months
 }

但我想要一个这样的结果:

 {
   Name : Fahad Subzwari,
   TotalExperience: 20 Months
 }

2 个答案:

答案 0 :(得分:0)

distinct关键字可能就是您所需要的。它允许从查询结果中过滤重复项。

可以找到更多信息here

您的select语句与distinct之后select关键字的少量添加相同。

答案 1 :(得分:0)

您可以在DISTINCT

中使用GROUP_CONCAT()
SELECT GROUP_CONCAT(DISTINCT CONCAT(aper.FirstName,' ',aper.LastName)) AS Name, 
GROUP_CONCAT(DISTINCT apro.totalExperience)  totalExperience
FROM applicant_personal_info aper 
INNER JOIN applicant_professional_info apro ON aper.ApplicantID = apro.ApplicantID
GROUP BY aper.ApplicantID

DEMO

示例输出

=================================
Name            totalExperience  
--------------  -----------------
Fahad Subzwari  20 Months  
=================================