DQL (Doctrine Query Language) - Conditional expressions - Subqueries.php 1.14 KB
Newer Older
hansbrix's avatar
hansbrix committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
A subquery can contain any of the keywords or clauses that an ordinary SELECT query can contain.



Some advantages of the subqueries:

* They allow queries that are structured so that it is possible to isolate each part of a statement.

* They provide alternative ways to perform operations that would otherwise require complex joins and unions.

* They are, in many people's opinion, readable. Indeed, it was the innovation of subqueries that gave people the original idea of calling the early SQL “Structured Query Language.”



<code type="php">
// finding all users which don't belong to any group 1
$query = "FROM User WHERE User.id NOT IN 
                        (SELECT u.id FROM User u 
                         INNER JOIN u.Group g WHERE g.id = ?";
                         
$users = $conn->query($query, array(1));

// finding all users which don't belong to any groups
// Notice: 
// the usage of INNER JOIN
// the usage of empty brackets preceding the Group component

$query = "FROM User WHERE User.id NOT IN 
                        (SELECT u.id FROM User u 
                         INNER JOIN u.Group g)";

$users = $conn->query($query);
</code>