简体   繁体   English

MySQL 一对多和多对多查询

[英]MySQL One to Many and Many to Many Query

I have three tables: Hospitals, Inspections, and Violations.我有三个表:医院、检查和违规。 I need to formulate a query that returns all lighting violations with the inspection date, inspectors notes, and hospital name in one row per inspection.我需要制定一个查询,在每次检查的一行中返回所有照明违规以及检查日期、检查员注释和医院名称。

A Hospital can have zero or more inspections.医院可以进行零次或多次检查。 Inspections can have zero or more violations.检查可以有零次或多次违规。

This is the query so far:这是到目前为止的查询:

SELECT h.hospital_name AS Name, i.date AS Date, CONCAT_WS(', ', v.notes) AS Notes
FROM hospital_table h
LEFT JOIN inspection_table i ON h.id = i.hospital_id
INNER JOIN violation_table v ON i.id = v.inspection_id
WHERE v.type = 'Lighting'
ORDER BY i.date DESC;

There are instances where an inspection will have zero or more lighting violations.在某些情况下,检查会出现零个或多个照明违规。 Essentially I need the result to look like:基本上我需要结果看起来像:

| Name              | Date         | Notes                           |
----------------------------------------------------------------------
| Burnaby General   | 18-09-2107   | Bath light..., bed sconce...    |

The result is close but in some cases, the dates are not correct.结果很接近,但在某些情况下,日期不正确。 Can someone suggest a way to achieve what is required?有人可以提出一种实现所需的方法吗?

Use GROUP_CONCAT instead of CONCAT_WS to get all notes per hospital in one row.使用GROUP_CONCAT而不是CONCAT_WS将每家医院的所有注释放在一行中。

SELECT h.hospital_name AS `name`, 
i.date AS `date`, 
GROUP_CONCAT(v.notes) AS Notes
FROM hospital_table h
LEFT JOIN inspection_table i ON h.id = i.hospital_id
LEFT JOIN violation_table v ON i.id = v.inspection_id
WHERE v.type = 'Lighting'
GROUP BY h.hospital_name
ORDER BY i.date DESC;

Note: The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet.注意:结果被截断为 group_concat_max_len 系统变量给定的最大长度,其默认值为 1024。该值可以设置得更高,尽管返回值的有效最大长度受 max_allowed_pa​​cket 的值限制.

For date i assume there will be multiple inspections per hospital to get the recent inspection date you can use MAX(i.date) and change ORDER BY MAX(i.date) or to get all inspection dates you can apply GROUP_CONCAT on i.date too对于日期,我假设每家医院都会进行多次检查以获得最近的检查日期,您可以使用MAX(i.date)并更改ORDER BY MAX(i.date)或获取所有检查日期,您可以在 i.date 上应用GROUP_CONCAT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM