0

我有一个正在处理的查询,我正在从表 tblmovementhyst 中获取每个 socialSecurityNumber 的最大记录。这很好用,但是我想重新加入到citizen 表中以显示tblcitizens 表中但tblmovementhyst 中不存在的记录。

tblcitizen 的主键是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`)

公民

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`)
4

1 回答 1

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。

于 2013-05-05T20:26:34.050 回答