Skip to content
PHP Logo

How can SQL DISTINCT or GROUP BY clauses be utilized to prevent duplicate entries in a MySQL query result when using LEFT JOINs?

When using LEFT JOINs in a MySQL query, duplicate entries may appear in the result set if there are multiple matching rows in the joined table. To prevent this, you can use the SQL DISTINCT or GROUP BY clauses to eliminate duplicates based on a specific column or set of columns. By using these clauses, you can ensure that each row in the result set is unique.

php
$query = "SELECT DISTINCT column1, column2 FROM table1 LEFT JOIN table2 ON table1.id = table2.id";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        // Process each unique row
    }
}