Lavorare con Join e Sottoquery

Eseguire query su un database PostgreSQL in Java

Miller Trujillo

Staff Software Engineer

Dati in più tabelle

  • books, authors, categories, book_reviews
  • Necessità di combinare dati tra tabelle

Relazioni nel database della biblioteca

Eseguire query su un database PostgreSQL in Java

Unire Tabelle

String sql = "SELECT b.title, a.first_name, a.last_name " +
             "FROM books b " +

"INNER JOIN book_authors ba ON b.book_id = ba.book_id " + "INNER JOIN authors a ON ba.author_id = a.author_id " +
"WHERE b.publication_year > ?";
PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 2010); ResultSet rs = pstmt.executeQuery();
| title                                              | first_name | last_name |
| -------------------------------------------------- | ---------- | --------- |
| Effective Java                                     | Joshua     | Bloch     |
| Designing Data-Intensive Applications              | Martin     | Kleppmann |
Eseguire query su un database PostgreSQL in Java

INNER vs LEFT JOIN

-- INNER JOIN: solo corrispondenze
SELECT b.title, r.rating
FROM books b
INNER JOIN book_reviews r 
    ON b.book_id = r.book_id;
-- LEFT JOIN: tutte le righe a sinistra
SELECT b.title, r.rating
FROM books b
LEFT JOIN book_reviews r 
    ON b.book_id = r.book_id;

Join Interno e Sinistro

Eseguire query su un database PostgreSQL in Java

Sottoquery

// Estrazione del libro pubblicato più di recente
String sql = "SELECT title FROM books " +
             "WHERE publication_year = ( " +

" SELECT MAX(publication_year) FROM books " + ")";
PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery();
| title                                              |
| -------------------------------------------------- |
| Effective Java                                     |
| Refactoring: Improving the Design of Existing Code |
Eseguire query su un database PostgreSQL in Java

Sottoquery con Parametri

// Estrazione di tutti i libri "Fantasy"
String sql = "SELECT title FROM books " +
             "WHERE category_id IN ( " +

" SELECT category_id FROM categories WHERE name = ? " + ")";
PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, "Fantasy"); ResultSet rs = pstmt.executeQuery();
| title                                    |
| ---------------------------------------- |
| The Way of Kings                         |
| Harry Potter and the Philosopher's Stone |
Eseguire query su un database PostgreSQL in Java

StringBuilder

  • La concatenazione di stringhe con + è lenta e difficile da leggere
  • append() aggiunge testo, toString() restituisce il risultato
StringBuilder sb = new StringBuilder("SELECT * FROM ");

sb.append("books");
sb.append(" WHERE 1=1");
sb.toString(); // SELECT * FROM books WHERE 1=1
Eseguire query su un database PostgreSQL in Java

Ayo berlatih!

Eseguire query su un database PostgreSQL in Java

Preparing Video For Download...