Are there any best practices for optimizing and structuring complex SQL queries in PHP?

When dealing with complex SQL queries in PHP, it's important to optimize and structure them properly to ensure efficiency and maintainability. One best practice is to break down the query into smaller, manageable parts using subqueries or temporary tables. Additionally, using parameterized queries can help prevent SQL injection attacks and improve performance.

<?php
// Example of optimizing and structuring a complex SQL query in PHP

// Define the main query
$query = "SELECT * FROM table1 WHERE id IN (SELECT id FROM table2 WHERE condition = :condition)";

// Prepare the statement
$stmt = $pdo->prepare($query);

// Bind parameters
$stmt->bindParam(':condition', $condition);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();

// Process the results
foreach ($results as $result) {
    // Do something with the data
}
?>