我有一个名为book的数据库表。列是:id,author,title,isbn,collection_name,collection_id,volume_number,owner_id,can_be_borrowed。所有者表包括列:名称,ID,地址,观察。
owner_id是映射到所有者表中的id的外键。
集合可以在书表中多次出现。例如,可能有5份哈利波特系列。其中两个集合可以具有can_be_borrowed = true,而其他3个集合可以具有can_be_borrowed = false。此外,collection_id对于每个集合实例都是唯一的。这意味着每个哈利波特系列都会有不同的collection_id。但是它们都具有相同的collection_name。
因此,给定owner_id,我想查找属于该所有者的所有集合。约束是:
现在,请耐心等待。我的SQL生疏了。这是我得到的信息:
select o.address, o.id, b.*,
bool_or(can_be_borrowed)
from owner o, book b
where b.collection_name in (select collection_name
from owner o2, b2
where o2.id=${owner_id}
and o2.id=b2.id)
and volume=1
group by b.collection_name
子查询查找属于提供的所有者的所有collection_name。外部查询搜索找到的collection_names集合中的所有卷1。然后为了确保我们每个集合只获得一个项目,我们按collection_name分组。最后,为了确保我们知道是否可以借用集合,我们在can_be_borrowed上汇总。
现在,这个查询有一个问题:我不能简单地按collection_name分组。显然我也必须按照select语句中的所有其他列进行分组。如果我这样做,我得到一堆重复,结果根本不是我想要的。如何使此查询有效?
我会删除“分组依据”,因为这不是您所需结果的正确操作。
你想要的是“选择DISTINCT ...”,每个“set”只能获得1行。
==============修改后的答案============================
对于此数据集:
拥有者:
图书:
这个选择会做你想要的,除非它返回第1卷的实际can_be_borrowed,如果任何音量的can_be_borrowed = 1(真)
样本所有者= 1
select o.address, o.id, o.name, b.*
from owners o, books b
where o.id=b.owner_id
and o.id=1
and b.volume_number=1
and b.collection_id in (select distinct b2.collection_id
from books b2, owners o2
where b2.owner_id=o2.id and b2.can_be_borrowed=1)
结果:
样本所有者= 2
select o.address, o.id, o.name, b.*
from owners o, books b
where o.id=b.owner_id
and o.id=2
and b.volume_number=1
and b.collection_id in (select distinct b2.collection_id
from books b2, owners o2
where b2.owner_id=o2.id
and b2.can_be_borrowed=1)
结果:
你是正确的轨道,这是greatest-n-per-group,但你实际上并没有限制你的“书”行,这意味着你仍然有一个全n组的情况(volume=1
只是一个卷,而不是“最大的” “ 这里)。
在这种情况下,甚至是“群体”,“最伟大的”是什么?显然,qazxsw poi是衡量“伟大”的标准,qazxsw poi是我们的团队。
有了它,编写查询相当容易:
can_be_borrowed
collection_name