De eerste join
CityBook Libraries wil boekcategorieën naast zoekresultaten tonen. Alleen boeken met toegewezen categorieën mogen in de resultaten verschijnen.
Voeg de tabel categories toe om de boekgegevens te verrijken. De klasse HikariSetup is al voor je geconfigureerd.
Deze oefening maakt deel uit van de cursus
Query's uitvoeren op een PostgreSQL-database in Java
Oefeninstructies
- Maak de query af om te joinen met de tabel
categoriesviacategory_id. - Kies het juiste type join om alleen boeken te tonen die een categorie hebben.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
public class Main {
public static void main(String[] args) throws SQLException {
HikariDataSource ds = HikariSetup.createDataSource();
// Join with the categories table using category_id
String query = """
SELECT b.*, c.name, c.description
FROM books b
____ JOIN ____ c on b.____ = c.____
WHERE b.publication_year >= ?
AND b.status = 'available'
ORDER BY publication_year ASC
""";
try (Connection conn = ds.getConnection();
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setInt(1, 2000);
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
System.out.printf("ID: %d, Title: %s (%d), Category: %s - %s%n",
rs.getInt("book_id"), rs.getString("title"), rs.getInt("publication_year"),
rs.getString("name"), rs.getString("description"));
}
}
}
}
}