Cómo combinar varias tablas

I have three tables which I want to combine into one view or temporary table, they are a pupil table:

| id | UPN |   

A snapshot table:

| id | PupilID | Surname | Forename | AssessmentYr |  

A results table:

|  id |  PupilID  | KS1RdTA |  KS1WrTA |  

The id in the pupil table matches with PupilID in the snapshot and results, in the snapshot table there may be more than one entry with the same PupilID.

There may not be any match in either the pupil or results table.

My question is how to write a query which will take every entry in the snapshot table, regardless of whether it is matched with anything in the pupil or results table, but, where possible, match it up.

I want to either make this into a temporary table or a view for subsequent manipulation and would welcome some suggestions on which would work best.

Gracias de antemano por su ayuda.

preguntado el 30 de enero de 12 a las 20:01

1 Respuestas

You did not specify if the results table may be missing rows for some records in the pupil table, but I believe this is what you're looking for:

SELECT
  pupil.UPN,
  pupil.id,
  snapshot.Surname,
  snapshot.Forename, 
  snapshot.AssessmentYr,
  results.KS1RdTA,
  results.KS1WrTA
FROM
  pupil LEFT JOIN snapshot ON pupil.id = snapshot.PupilID
  LEFT JOIN results ON pupil.id = results.PupilID

If I am misunderstanding, and it is related rows from the pupil table which may be missing from snapshot (that is, a NULL PupilID in snapshot, then this may be the correct query, using a different LEFT JOIN which prefers snapshot encima pupil.

SELECT
  pupil.UPN,
  pupil.id,
  snapshot.Surname,
  snapshot.Forename, 
  snapshot.AssessmentYr,
  results.KS1RdTA,
  results.KS1WrTA
FROM
  snapshot LEFT JOIN pupil ON snapshot.PupilID = pupil.id
  LEFT JOIN results ON snapshot.PupilID = results.PupilID

Respondido el 31 de enero de 12 a las 00:01

Thanks, actually there may be missing rows in both the pupil and results table. - Essex Steph

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.