Skip to content
Advertisement

(SQL) Pulling linked profiles from two tables using Knex

I currently have two tables with the following data:

Parent: ID, Name, PIN
Child: ID, Name, PIN, ParentID

I currently have my query set up like this with Knex:

db('Parents AS P')
    .join('Children AS C', 'C.ParentID', 'P.ID')
    .where('C.ParentID', ID)
    .select([
      'C.PIN AS ChildPIN',
      'C.Name AS ChildName',
      'P.Name AS ParentName',
      'P.PIN AS ParentPIN',
    ])

I’m currently parsing the data into the following format:

[
  { Name: 'Name1', PIN: '1234', type: 'Parent' },
  { Name: 'Name2', PIN: '2345', type: 'Child' }
]

This works totally fine except for the cases where the parent has no children, as it won’t pull any data at all, including parent info. Is there any workaround in this case to avoid having to do a second API request? Thank you!

Advertisement

Answer

use Left Outer Join instead of join

db('Parents AS P')
  .leftOuterJoin('Children AS C', 'C.ParentID', 'P.ID')
  .where('C.ParentID', ID)
  .select([
    'C.PIN AS ChildPIN',
    'C.Name AS ChildName',
    'P.Name AS ParentName',
    'P.PIN AS ParentPIN',
])

EDIT:

This was solved by using a left INNER join instead of outer! Thanks again!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement