如何比较两个表的计数

How to compare count of two tables

尝试比较两个 table 的计数时遇到问题(使用 SQLite)。

假设我有 table 个像:

对象(NumId是主键

NumId Object_category
1 permanent
2 borrowed
3 borrowed
4 borrowed
5 borrowed

借来的 (NumObj 是 Foreign Key/Primary Key 引用对象 table)

NumObj Collection_name
2 collection_alpha
3 collection_betha
4 collection_betha
5 collection_betha

我需要执行的查询是:

"What are the collections with higher number of borrowed objects than quantity of permanent objets?"

我目前的尝试是:

SELECT Collection_name FROM Borrowed
WHERE (SELECT COUNT(Collection_name) FROM Borrowed)> 
(SELECT COUNT(*) FROM Objects WHERE Object_category = 
'permanent')

它从列中返回值,没有按预期工作(本应返回 'collection_betha' 因为拥有 3 个对象,大于现有永久对象的数量 1)。

我会在这里使用条件聚合:

SELECT b.Collection_name
FROM Borrowed b
INNER JOIN Objects o
    ON o.NumId = b.NumObj
GROUP BY b.Collection_name
HAVING SUM(o.Object_category = 'borrowed') > SUM(o.Object_category = 'permanent');

也许加入会有所帮助

SELECT Borrowed.Collection_name
FROM Borrowed 
JOIN Objects 
ON Objects.NumId= Borrowed.NumObj
GROUP BY Borrowed.Collection_name 
HAVING COUNT(NumObj) > 
(SELECT COUNT(*) FROM Objects WHERE Object_category = 'permanent')