MySql Join返回没有空值的现有记录

时间:2013-05-05 18:06:45

标签: mysql sql left-join toad

我正在处理一个查询,我正在从表tblmovementhyst获取每个socialSecurityNumber的最大记录。这工作正常,但我想加入回公民表,以显示在tblcitizens表中但在tblmovementhyst中不存在的记录。

tblcitizens的主键是socialSecurityNumber,而tblmovementhyst的主键是citizenPositionNo。以下是我迄今所拥有的代码:

SQL

 select m.citizenSocialSecurityNumber,CONCAT(c.fName,' ',c.lName)as name, 
CONCAT(m.latAdd,',',m.longAdd)as latlng, t.citizenTypeId,max(m.citizenPositionNo)as positionNo

from tblcitizens c LEFT JOIN tblcitizenType t
  ON c.citizenTypeId = t.citizenTypeId

LEFT JOIN tblmovementhyst m
  ON m.citizenSocialSecurityNumber = c.socialSecurityNumber;

tblmovementhyst

TABLE `tblmovementhyst` (
  `citizenPositionNo` int(11) NOT NULL AUTO_INCREMENT,
  `citizenSocialSecurityNumber` int(11) NOT NULL,
  `latAdd` decimal(18,14) NOT NULL,
  `longAdd` decimal(18,14) NOT NULL,
  `date` varchar(10) NOT NULL,
  `time` time NOT NULL,
  PRIMARY KEY (`citizenPositionNo`)

tblcitizens

TABLE `tblcitizens` (
  `socialSecurityNumber` int(11) NOT NULL,
  `fName` varchar(30) NOT NULL,
  `lName` varchar(30) NOT NULL,
  `oName` varchar(30) DEFAULT NULL,
  `citizenTypeId` int(11) NOT NULL,
  `dob` date NOT NULL,
  PRIMARY KEY (`socialSecurityNumber`)

1 个答案:

答案 0 :(得分:1)

你应该使用LEFT JOIN,它返回第一个表中的所有行,只返回第二个表中匹配的行:

SELECT ..., MAX(m.citizenPositionNo) AS positionNo
FROM
  tblcitizens c LEFT JOIN tblcitizenType t
  ON c.citizenTypeId = t.citizenTypeId
  LEFT JOIN tblmovementhyst m
  ON m.citizenSocialSecurityNumber = c.socialSecurityNumber
GROUP BY
  ...

如果在tblcitizens上有记录而在tblmovementhyst上没有记录,则MAX(citizenPositionNo)将为NULL。