试图让我的头围绕一个可能真的很简单的查询。它涉及我正在连接的两个表,但需要根据web界面中的用户选择过滤其结果。
表"报告":
<表类>report_id (PK, int) report_name (varchar) tbody><<tr>1 报告1 2报告2 3 报告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
我假设policies
中policy_report_id
和policy_type
的组合是唯一的,并且policy_type
不可为空。