首页 > 解决方案 > 从具有空数据记录的类型表中选择 *

问题描述

Types
ID | Title
1  | blue
2  | red

Colours
ID| patientID | date |Type
1 | 1         | 2019 |1
2 | 1         | 2019 |2
3 | 2         | 2018 |1 

即使记录的类型不存在,我也需要记录,它应该带回 null。因此,即使只有 1 条记录,患者 2 也应该带回 2 条记录。

Select Title,date from Colours Left Join Types On Colours.Type = Types .ID Where patient.ID = 1
{
  patient1:[{
             Title: blue
             date : 2019
           },
           { 
             Title: red,
             date : 2019
           }]
 }

但是,我需要患者 2 恢复所有颜色为空值的日期。目前获得:

Select Title,date from Colours Left Join Types On Colours.Type = Types .ID Where patient.ID = 2
patient:[{
            Title: blue
            date : 2018
         }]

但是我需要:

  patient:[{
             Title: blue
             date : 2018
           },
           { 
             Title: red,
             date : null
           }]
 }

标签: mysqlsql

解决方案


我想你想要一个left join

select t.Title, c.date
from types t left join
     Colours c
     On c.Type = t.ID and c.patientID = 2;

推荐阅读