(SQL) 使用 Knex 从两个表中提取链接配置文件

(SQL) Pulling linked profiles from two tables using Knex

我目前有两个包含以下数据的表:

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

我目前使用 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',
    ])

我目前正在将数据解析为以下格式:

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

除了 parent 没有 children 的情况外,这完全可以正常工作,因为它根本不会提取任何数据,包括 parent 信息。在这种情况下是否有任何解决方法来避免必须执行第二个 API 请求?谢谢!

使用 Left Outer Join 而不是 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',
])

编辑:

这已通过使用左内连接而不是外连接解决!再次感谢!