mySQL主表与子表一对多关系,left join关联查询子表中其中一条记录

1、left join测试示例

SELECT
	a.id,
	a.create_name,
	a.create_time,
	b.id AS bId,
	b.charge_key,
	b.check_status 
FROM
	patient_check_list a
	LEFT JOIN patient_check_item b ON b.business_id = a.id

mySQL主表与子表一对多关系,left join关联查询子表中其中一条记录_第1张图片

主表和子表通过LEFT JOIN 关联后,主表以重复的方式对应多条右表记录。

2、实现主表与子表一对一对应。

2.1 使用group by ,找出右表一条记录与主表关联

SELECT
	a.id,
	a.create_name,
	a.create_time,
	b.id AS bId,
	b.charge_key,
	b.check_status 
FROM
	patient_check_list a
	LEFT JOIN ( SELECT id, business_id, charge_key, check_status FROM patient_check_item GROUP BY business_id ) b ON b.business_id = a.id

mySQL主表与子表一对多关系,left join关联查询子表中其中一条记录_第2张图片

2.2 使用group by 和 min或max聚合函数,找出右表最新或最旧的一条记录与主表关联

SELECT
	a.id,
	a.create_name,
	a.create_time,
	b.id AS bId,
	b.charge_key,
	b.check_status 
FROM
	patient_check_list a
	LEFT JOIN ( SELECT id, business_id, charge_key, check_status FROM patient_check_item WHERE id IN ( SELECT MAX( id ) FROM patient_check_item GROUP BY business_id ) ) b ON b.business_id = a.id

mySQL主表与子表一对多关系,left join关联查询子表中其中一条记录_第3张图片

2.3 使用group_concat 

SELECT
	a.id,
	a.create_name,
	a.create_time,
	b.id AS bId,
	b.charge_key 
FROM
	patient_check_list a
	LEFT JOIN ( SELECT id, business_id, GROUP_CONCAT( charge_key SEPARATOR '_' ) AS charge_key FROM patient_check_item GROUP BY business_id ) b ON b.business_id = a.id

mySQL主表与子表一对多关系,left join关联查询子表中其中一条记录_第4张图片

 

你可能感兴趣的:(数据库,mysql,sql,数据库)