mysql uses join with aggregate function

巴扎黑
Release: 2017-05-11 10:52:12
Original
1642 people have browsed it

Aggregation functions are used to summarize data. Although all examples of aggregate functions so far have only summarized data from a single table, these functions can also be used with joins. To illustrate this, consider an example. If you want to retrieve all customers and the number of orders placed by each customer, the following code using the COUNT() function can do the job:

Input:

select customers.cust_name,customers.cust_id,count(order_num) as num_ord from customers inner join orders on customers.cust_id = orders.cust_id group by custo,=mers.cust_id;
Copy after login

Output:

mysql uses join with aggregate function

# Analysis: This SELECT statement uses INNER JOIN to relate the customers and orders tables to each other. The GROUP BY clause groups the data by customer, so the function call COUNT(orders.order_num) counts the orders for each customer, returning it as num_ord.

Aggregation functions can also be easily used with other joins. Please look at the following example:

Input:

select customers.cust_name,customers.cust_id,count(order_num) as num_ord from customers left outer join orders on customers.cust_id = orders.cust_id group by custo,=mers.cust_id;
Copy after login

Output:

mysql uses join with aggregate function

mysql uses join with aggregate function

Analysis: This The example uses a left outer join to include all customers, even those who have not placed any orders. The results show that the customer Mouse House is also included, and it has 0 orders.

The above is the detailed content of mysql uses join with aggregate function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!