【发布时间】:2021-01-28 15:55:42
【问题描述】:
我没有尝试过 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 和 count。 我尝试了这个请求,但是响应不好(返回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';
有什么想法吗? 谢谢
【问题讨论】:
-
请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入作为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出尽可能少的代码,即您显示的代码可以通过您显示的代码扩展为不正常的代码。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)的 SQL,并以表格格式作为代码输入。 How to Ask 暂停总体目标的工作,将代码砍到第一个表达式,没有给出你期望的内容,说出你期望的内容和原因。
标签: sql postgresql count inner-join having-clause