Domanda

I have a query i am working on and i am taking the max records for each socialSecurityNumber from a table tblmovementhyst. This works fine however i would like to join back to the citizen table to display also records that are in the tblcitizens table but does not exist in the tblmovementhyst.

The primary key for the tblcitizens is socialSecurityNumber and the primary key for tblmovementhyst is citizenPositionNo. Under is he code of what i have thus far:

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`)
È stato utile?

Soluzione

You should use a LEFT JOIN, that returns all rows from the first table and only the rows that matches on the second one:

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
  ...

In case that there is a record on tblcitizens but not on tblmovementhyst, MAX(citizenPositionNo) will be NULL.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top