我有以下关系:
C(id,n) I(ID,克) IB(I_id,c_id,r)
我想列出关系“C”中的所有“n”,其中r等于'H',最大“g”等于't'
样本数据如下:
C:
C_ID,N
c1,N1
c2,N2
c3,N3
IB:
C_ID,I_ID,R
c1,i1,H
c1,i2,H
对于c1,c1,i3,N max H是t和m
c2,i1,N
c2,i2,H
C2的c2,i3,N max H是m
c3,i1,H
c3,i2,H
对于c3,c3,i3,H max H是t
I:
I_ID,G
i1,t
i2,m
i3,t
对于此样本数据,c1和c3对于't'
具有最大'H'
以下查询是一个答案,但似乎没有优化且非常沉重:
SELECT c1.n
FROM I ib1, C c1, I i1
WHERE i1.I_ID = ib1.I_ID
AND i1.g IN
(SELECT i.g
FROM IB ib, C c, I i
WHERE i.id = ib.I_id
AND c.id = ib.C_id
AND ib.r = 'H'
AND i.g = 't'
AND c.id = c1.id
GROUP BY i.g, c.id
HAVING COUNT(*)=(
SELECT max(COUNT(*))
FROM IB ib, C c, I i
WHERE i.id = ib.I_id
AND c.ID = ib.C_id
AND ib.r = 'H'
AND c.id = c1.id
GROUP BY i.g, c.id))
GROUP BY c1.id, c1.name;
很高兴告诉我其他可能的解决方案以及如何优化查询。同样值得帮助我的桌面设计。 感谢
答案 0 :(得分:1)
如果我理解正确,通过我们得到每个c.id,ig的计数组,那么我们按行数按降序排列行数,我们只得到第一行ig ='t'
SELECT DISTINCT c1.n
FROM C c1
WHERE c1.c_id IN (SELECT DISTINCT x.c_id
FROM (SELECT c_id, g, RANK () OVER (PARTITION BY c_id ORDER BY cnt DESC) rnmbr
FROM ( SELECT c.c_id, i.g, COUNT (*) cnt
FROM IB ib, C c, I i
WHERE i.i_id = ib.I_id AND c.c_ID = ib.C_id AND ib.r = 'H'
GROUP BY i.g, c.c_id)) x
WHERE g = 't' AND rnmbr = 1)