MySQL从连接表中获取行,如果存在这样的类型



试图让我的头围绕一个可能真的很简单的查询。它涉及我正在连接的两个表,但需要根据web界面中的用户选择过滤其结果。

表"报告":

<表类>report_id (PK, int)report_name (varchar)tbody><<tr>1报告12报告23报告3

您可以使用聚合并在HAVING子句中设置条件:

SELECT policy_report_id
FROM policies
GROUP BY policy_report_id
HAVING SUM(policy_type <> 1) = 0; -- no other than policy_type = 1

或:

HAVING SUM(policy_type <> 2) = 0; -- no other than policy_type = 2

如果您同时需要策略1和2而不需要其他策略:

HAVING COUNT(*) = 2 AND SUM(policy_type NOT IN (1, 2)) = 0; 

上面的查询可以连接到reports以获得每个报告的详细信息:

SELECT r.*
FROM reports r
INNER JOIN (
SELECT policy_report_id
FROM policies
GROUP BY policy_report_id
HAVING SUM(policy_type <> 1) = 0
) p ON p.policy_report_id = r.report_id

我假设policiespolicy_report_idpolicy_type的组合是唯一的,并且policy_type不可为空。

相关内容