我有下表:
床垫: id(PK),idUser(FK)healthSystemName,建筑物,楼层,房间,床,参考号
患者: id(PK),idMattress(FK),idUSer(FK),姓名,姓氏,性别,生日,medicalRecordNumber,visiterRecordNumber,strees,城市,邮政编码,国家/地区,maxPressureTolerance
PressureMap: id(PK),idMattress(FK),pressureData,maxPressure,状态,bodyPosition,created_at,updated_at
我想知道我需要使用以下查询来获得以下视图:
Patient.name,Patient.surname,Patient.medicalRecordNumber,Patient.visitRecordNumber,Mattress.room,Mattress.id,PressureMap.pressureData(仅由created_at 最新提供),PressureMap。存在
现在,我有以下查询:
SELECT p.name
, p.surname
, p.medicalRecordNumber
, p.visitRecordNumber
, m.room
, m.id mattressID
FROM mattress m
LEFT
JOIN patient p
on p.idMattress = m.id
我在哪里分组我需要桌子床垫和桌子病人,但我不知道如何仅在最后一个条目中添加pressureMap数据。因此,我获得了绿色数据,我需要知道如何添加黄色数据。
谢谢!
答案 0 :(得分:0)
我找到了使用Laravel查询构建器解决该问题的方法。
$latestPressureMap = DB::table('pressuremap')
->select('idMattress', DB::raw('MAX(created_at) as last_pressureMap_created_at'), 'presence', 'maxPressure')
->groupBy('idMattress');
$mattress = DB::table('mattress')
->leftJoinSub($latestPressureMap, 'latest_pressureMap', function ($join) {
$join->on('mattress.id', '=', 'latest_pressureMap.idMattress');
})
->leftJoin("patient","mattress.id","=","patient.idMattress")
->select("patient.id", "patient.name", "patient.surname", "patient.medicalRecordNumber", "patient.visitRecordNumber", "mattress.id", "mattress.healthSystemName","mattress.building","mattress.floor","mattress.room", "mattress.bed", "patient.gender", "latest_pressureMap.presence", "latest_pressureMap.last_pressureMap_created_at","latest_pressureMap.maxPressure")
->where('mattress.idUser', '=', $id)
->get();
return view('dashboard',['mattress' => $mattress]);