What is the purpose of the "GROUP BY" clause in a MySQL query and how does it affect the results?
The "GROUP BY" clause in a MySQL query is used to group rows that have the same values into summary rows. It is often used with aggregate functions like COUNT, SUM, AVG, etc. to perform calculations on the grouped data. This clause affects the results by organizing the data into groups based on the specified column(s) and allowing you to perform aggregate functions on those groups.
$query = "SELECT column1, COUNT(column2)
FROM table_name
GROUP BY column1";
$result = mysqli_query($connection, $query);
// Loop through the results
while($row = mysqli_fetch_assoc($result)) {
echo $row['column1'] . ": " . $row['COUNT(column2)'] . "<br>";
}
Keywords
Related Questions
- What are some common pitfalls to avoid when setting up a SQL server on a root server for PHP development?
- Are there any best practices for handling database connections in PHP scripts to avoid errors like the one mentioned in the thread?
- How can images be read from a directory in PHP and sorted automatically to ensure a specific order is maintained?