Home > Database > Mysql Tutorial > How to Retrieve All Categories and Their Minimum/Maximum Product Prices in MySQL, Even When Some Categories Have No Products?

How to Retrieve All Categories and Their Minimum/Maximum Product Prices in MySQL, Even When Some Categories Have No Products?

Linda Hamilton
Release: 2024-12-04 16:25:16
Original
677 people have browsed it

How to Retrieve All Categories and Their Minimum/Maximum Product Prices in MySQL, Even When Some Categories Have No Products?

Selecting from Two Tables with Unequal Rows in MySQL

In an online shopping database with two tables - categories and products - a common task is to retrieve all categories along with the minimum and maximum product prices in each category. However, a straightforward query encounters an issue: categories without products are excluded from the results.

To address this challenge, it's necessary to use an outer join instead of an implicit join. An outer join allows rows from one table (in this case, categories) to be retrieved even if there are no corresponding rows in the other table (products). Specifically, a left join is used here, so that all categories are included in the results.

Additionally, to replace null values with 0 for categories with no products, the IFNULL() function is employed. This function takes the value of the expression provided in the first argument, and if it's null, returns the value specified in the second argument instead.

The updated query syntax is as follows:

SELECT
    sc.*,
    IFNULL(MIN(s.price), 0) AS minp,
    IFNULL(MAX(s.price), 0) AS maxp
FROM categories AS sc
LEFT JOIN products AS s
ON s.ownerid = sc.id
GROUP BY sc.id
Copy after login

By using an outer join and the IFNULL() function, we can retrieve all categories and ensure that categories with no products are represented with minp and maxp values of 0. This query effectively handles the need to select from two tables even when not all rows in one table have corresponding entries in the other.

The above is the detailed content of How to Retrieve All Categories and Their Minimum/Maximum Product Prices in MySQL, Even When Some Categories Have No Products?. For more information, please follow other related articles on the PHP Chinese website!

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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template