如何解决优化的SQL选择,可跨多个表进行选择
我有下表(使用SQLite测试)。
create table group_header (id int,minCount int,maxCount int);
create table group_items(id int,group_id int,product varchar(10),cons varchar(10));
group_header具有以下记录:
id|minCount|maxCount
1|2|2
group_items具有以下记录:
id|group_id|product|cons
1|1|A|optional
2|1|B|optional
3|1|C|required
4|1|D|optional
SQL查询应返回满足以下条件的group_header id:
- 输入将是一个或多个产品(例如'A'和'C')
- SQL查询应检查以下条件:
-
minCount
产品应满足optional
(即输入中count
个项目中的optional
值应> =minCount
) - group_item表中的所有
required
产品都应存在于输入产品列表中
-
通过以下方法可以实现暴力破解:
select * from group_items where group_id = 1 and product in ('A') or cons='required';
,然后在SQL外部分别评估minCount
和required
。如果可以使用SQL以更优化的方式提出任何建议。
解决方法
如果我理解正确,这是一个带有having
子句的聚合。
select gh.id
from group_header gh left join
group_items gi
on gh.id = gi.group_id
group by gh.id
having sum( case when gi.cons = 'required' and gi.product in ('A') then 1 else 0 end) = 1 and
sum( case when gi.cons = 'optional' then 1 else 0 end) >= gh.mincount;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。