title: Need help refactoring queries/database design
body: <p>I'm working on a website which will be hosting a number of books written by myself. The book contents will be stored as HTML chunks in a database.</p>
  
  <p>A book contains several chapters, and each chapter contains several sections. I decided to give each book, chapter and section unique ID:s with the aim that I can move and delete sections freely and not having to update records.</p>
  
  <p>So the database looks like this:</p>
  
  <pre><code>books:
      book_id int
      book_name varchar
  
  chapters:
      book_id int references books.book_id
      chapter_id int
      chapter_no int
      chapter_name varchar // will probably be factored out to a separate table
  
  sections:
      chapter_id int references chapters.chapter_id
      section_no int
      section_id int references section_texts.section_id
  
  section_texts:
      section_id int
      section_text text
  </code></pre>
  
  <p>So for example section 5 in chapter 3 can point to the <code>section_text</code> which has <code>section_id</code> 79, and contains the text "Hello world!". Section 6 could have <code>section_id</code> 83 and so on.</p>
  
  <p>Now I want to create a PHP method which will, given a book name, chapter number and section number, retrieve for me the <code>section_text</code> that is there. What I have now is done in 4 steps:</p>
  
  <pre><code>function getText($bookName, $chapter, $section)
  {
      // retrieve book id
      $query = $this-&gt;db-&gt;query(
          sprintf('SELECT book_id
              FROM books` 
              WHERE book_name = %s;', $bookName));
  
  $row = $query-&gt;row();
  $bookId = $row-&gt;book_id;
  
  // retrieve chapter id
  $query = $this-&gt;db-&gt;query(
          sprintf('SELECT chapter_id
              FROM chapters` 
              WHERE book_id = %d AND chapter_no = %d;', $bookId, $chapter));
  
  $row = $query-&gt;row();
  $chapterId = $row-&gt;chapter_id;
  
  // retrieve section id
  $query = $this-&gt;db-&gt;query(
          sprintf('SELECT section_id
              FROM sections` 
              WHERE chapter_id = %d AND section_no = %d;', $chapterId, $section));
  
  $row = $query-&gt;row();
  $sectionId = $row-&gt;section_id;
  
  // retrieve section text
  $query = $this-&gt;db-&gt;query(
          sprintf('SELECT section_text
              FROM section_texts` 
              WHERE section_id = %d;', $sectionId));
  
  $row = $query-&gt;row();
  return $row-&gt;section_text;
  }
  </code></pre>
  
  <p>So for our example above, calling <code>getText("testBook", 3, 5)</code> should return the retrieved text, which was <code>Hello World!</code>.</p>
  
  <p>Although it works, it seems like the wrong way to go, creating 4 queries for fetching one section. This will be a small website so performance is not an issue, but I'm still interested in how this could be improved.</p>