[英]How to represent GROUP BY with HAVING COUNT(*)>1 in relational algebra?
[英]How to manage COUNT, GROUP BY and HAVING?
我没有在 SQL 中进行过实验,我尝试做一些不可能的事情。 SQL 给人这种感觉,可以仅在 1 个请求上执行此操作,但可能不是...
我有 4 个连接表 A -> S -> T -> F。一个简单的请求给我这些数据:
select a.id, s.id, t.type, f.name
from table_a a
inner join table_s s on a.id = s.id
inner join table_t t on t.id = s.t_id
inner join table_f f on f.id = t.f_id
where f.name = 'C';
a.id | s.id | t.type | f.name
-----------------------------
1 | 1 | E | C
1 | 2 | R | C
2 | 3 | E | C
3 | 4 | R | C
我想找到关联多个 S 行的所有 A id。 我想找到所有只有一个 S 行的 T 类型 = R 的 ID。
对于第一个,我做了这个 SQL 查询:
select a.id from table_a a
inner join table_s s on a.id = s.id
inner join table_t t on t.id = s.t_id
inner join table_f f on f.id = t.f_id
where f.name = 'C'
group by a.id
having count(s.*) > 1;
但是现在,对于第二个查询,我不明白如何过滤 t.type 和计数。 我尝试了这个请求,但响应不好(返回 a.id = 1)
select a.id from table_a a
inner join table_s s on a.id = s.id
inner join table_t t on t.id = s.t_id
inner join table_f f on f.id = t.f_id
where f.name = 'C'
group by a.id
having count(s.*) = 1 and t.type = 'R';
任何的想法 ? 谢谢
我想找到所有只有一个 S 行的 T 类型 = R 的 ID。
这是你想要的吗?
select a.id from table_a a
inner join table_s s on a.id = s.id
inner join table_t t on t.id = s.t_id
inner join table_f f on f.id = t.f_id
where f.name = 'C'
group by a.id
having count(*) = 1 and min(t.type) = 'R'
这为您提供只有一行的组,其类型为“R”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.