如何构造一个合适的SQL子查询?

时间:2017-04-28 04:28:54

标签: sql postgresql

我试图绕过如何做一个正确的子查询,这对我没有意义,让我说我有两个表bookschapters

图书

+----+------------------+----------+---------------------+
| id | name             | author   | last_great_chapters |
+----+------------------+----------+---------------------+
| 1  | some book title  | john doe |                   2 |
| 2  | foo novel title  | some guy |                   4 |
| 3  | other book title | lol man  |                   3 |
+----+------------------+----------+---------------------+

章节

+----+---------+----------------+
| id | book_id | chapter_number |
+----+---------+----------------+
| 1  | 1       | 1              |
| 2  | 1       | 3              |
| 3  | 1       | 4              |
| 4  | 1       | 5              |
| 5  | 2       | 1              |
| 6  | 2       | 2              |
| 7  | 2       | 3              |
| 8  | 2       | 4              |
| 9  | 2       | 5              |
| 10 | 3       | 1              |
| 11 | 3       | 2              |
| 12 | 3       | 3              |
| 13 | 3       | 4              |
| 14 | 3       | 5              |
+----+---------+----------------+

如何加入这两个表,并打印出" last_great_chapters"的行数(排序限制(last_great_chapters))。从每本书的书籍表列表?

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你想打印表格书和章节表中的last_great_chapters计数吗?

如果是,请尝试

select b.id, b.name, b.author , b.last_great_chapter, COUNT(c.chapter_number) as rownumbers FROM Books as b
    LEFT JOIN Chapters AS C ON c.chapter_number = b.last_great_chapters
    group by b.id, b.name, b.author , b.last_great_chapter