我有类似于以下数据库结构: ApplicationService表:
+-----+--------------+----------+---------------+
| id | name | status | application_id
| 1 | Service 1 | 1 | 24
| 2 | Service 2 | 2 | 24
| 3 | Service 3 | 3 | 25
+-----+--------------+----------+----------------
还有其他表格具有状态定义: CustomerStatus
+------------+--------------+----------+-----------+
| status_id | name | level | is_closed
| 1 | Status 1 | 2 | 1
| 2 | Status 2 | 1 | 0
| 3 | Status 3 | 3 | 1
+------------+--------------+----------+----------
ApplicationServices的每一行的状态计算为按application_id分组的记录中的最大级别状态。
因此,从ApplicationServices获取包含状态的所有记录将导致类似这样的内容:
+-----+--------------+----------+----------------+-------------+-----------
| id | name | status | application_id | status_name | is_closed
| 1 | Service 1 | 1 | 24 | Status 1 | 1
| 2 | Service 2 | 2 | 24 | Status 1 | 1
| 3 | Service 3 | 3 | 25 | Status 3 | 1
+-----+--------------+----------+----------------+-------------+-----------
是否有一种有效的方法将结果与按application_id分组的max(级别)附加到结果集的每一行?
答案 0 :(得分:1)
试试这个:
Y
答案 1 :(得分:0)
您可能必须执行子查询。子查询只是将两个表连接在一起,按application_id
分组/折叠,然后获取最大is_closed
值:
SELECT
t1.status AS `status`,
t1.application_id AS `app_id`,
MAX(t2.is_closed) AS `max_is_closed`
FROM applicationstatus AS t1
LEFT JOIN customerstatus AS t2 ON
t1.status = t2.status_id
GROUP BY t1.application_id
当您合并子查询时,is_closed
别名可以访问最大max_is_closed
值:
SELECT
t1.id AS id,
t1.name AS name,
t1.status AS `status`,
t1.application_id AS application_id,
t2.name AS status_name,
t3.max_is_closed
FROM applicationstatus AS t1
LEFT JOIN customerstatus AS t2 ON
t1.status = t2.status_id
LEFT JOIN
(SELECT
t1.status AS `status`,
t1.application_id AS `app_id`,
MAX(t2.is_closed) AS `max_is_closed`
FROM applicationstatus AS t1
LEFT JOIN customerstatus AS t2 ON
t1.status = t2.status_id
GROUP BY t1.application_id) AS t3 ON
t1.application_id = t3.app_id
查询的输出: