sql三重联接:计数上不明确的属性名称
所以我想计算书籍的数量,但是这些书籍存储在两个具有相同属性名称的不同表中。 我想要得到一个看起来像这样的结果:
name1 [total number of books of 1]
name2 [total number of books of 2]
我尝试了这个三重连接;
SELECT DISTINCT name, count(book)
FROM writes w
LEFT JOIN person p on p.id = w.author
LEFT JOIN book b on b.title = w.book
LEFT JOIN controls l on l.controller=p.id
GROUP BY name
ORDER BY name DESC
但由于 book 作为写入和控件中的属性存在,因此它无法执行查询。 只有当我省略其中一个连接以便它可以识别书籍时,它才能做到这一点。
我怎样才能告诉sql引擎计算每个人的两个书籍属性的数量?
So I want to count a number of books, but the books are stored in 2 different tables with the same attribute name.
I want to get a result that looks like:
name1 [total number of books of 1]
name2 [total number of books of 2]
I tried this triple join;
SELECT DISTINCT name, count(book)
FROM writes w
LEFT JOIN person p on p.id = w.author
LEFT JOIN book b on b.title = w.book
LEFT JOIN controls l on l.controller=p.id
GROUP BY name
ORDER BY name DESC
but since book exists as an attribute in writes and in controls, it cant execute the query.
It can only do it if I leave out one of joins so it can identify book.
How can I tell the sql engine to count the number of both book attributes together for each person?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为您感兴趣的数据库设计的结果,您应该发出 2 个不同的 sql,然后合并它们以处理单个输出。
A)
B)
出于您的目的,您可以获取 A 和 B 的 UNION。
或者您可以将它们用作第三条 SQL 上的数据源
As a result of database design that you interested in, you should issue 2 different sql and then merge them to handle single output.
A)
B)
For your purpose, you can get UNION of A and B.
or you can use them as data source on a third SQL
应该有效。
华泰
Should work.
HTH
这将根据每个不同作者的 ID 来确定他们写了多少本书。预聚合将返回每个作者的一条记录以及该作者的书籍数量。然后,加入 person 表以获取姓名。我将其保留为作者的 ID 和姓名的原因是...如果您有两个作者“John Smith”,但他们各自的 ID 为 123 和 389,您不会希望这些汇总到相同的值,该怎么办?人(或者你)。
This will work on a per distinct author's ID to how many books they've written. The pre-aggregation will return one record per author with how many books by that author. THEN, join to the person table to get the name. The reason I am leaving it by ID and Name of the author is... what if you have two authors "John Smith", but they have respective IDs of 123 and 389. You wouldn't want these rolled-up to the same person (or do you).