Home >Database >Mysql Tutorial >How to Retrieve Data from Two MySQL Tables with Missing Correspondents?

How to Retrieve Data from Two MySQL Tables with Missing Correspondents?

Linda Hamilton
Linda HamiltonOriginal
2024-12-04 03:36:11819browse

How to Retrieve Data from Two MySQL Tables with Missing Correspondents?

Selecting from Two Tables in MySQL with Missing Correspondents

To retrieve data from two tables in MySQL and handle cases where not all rows in one table have corresponding rows in the other, you can utilize an outer join. This approach differs from the outdated implicit join method and offers greater flexibility.

Consider the following example:

You have two tables, categories (with columns id and title) and products (with columns id, ownerid, title, and price, where ownerid references id in the categories table).

Your query aims to retrieve all categories and their minimum and maximum prices, grouped by category ID. However, the current query excludes categories without corresponding products.

To resolve this issue, employ a LEFT JOIN:

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

The LEFT JOIN ensures that all rows from the categories table are included, even if there are no corresponding rows in the products table. The IFNULL function assigns 0 to minp and maxp for categories without products, preventing NULL values from being displayed.

Alternatively, you may prefer to return NULL for these categories instead of 0, depending on your specific requirements.

The above is the detailed content of How to Retrieve Data from Two MySQL Tables with Missing Correspondents?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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