Home > Database > Mysql Tutorial > How to Retrieve One Product per Category Using JOIN with LIMIT 1?

How to Retrieve One Product per Category Using JOIN with LIMIT 1?

Susan Sarandon
Release: 2024-12-01 06:38:13
Original
374 people have browsed it

How to Retrieve One Product per Category Using JOIN with LIMIT 1?

Joining Tables with LIMIT 1 on the Joined Table

The task is to join two tables but retrieve only one record from the joined table per record in the first table. Consider the following tables:

categories (id, title)
products (id, category_id, title)
Copy after login

A simple query would join these tables as follows:

SELECT c.id, c.title, p.id AS product_id, p.title
FROM categories AS c
JOIN products AS p ON c.id = p.category_id
Copy after login

However, this returns multiple rows for each category, which is undesirable. We need to limit the results to one record from the products table per category.

One approach recommended in a similar question is to use a subquery to retrieve the primary key of the desired record:

SELECT
 c.id,
 c.title,
 p.id AS product_id,
 p.title AS product_title
FROM categories AS c
JOIN products AS p ON
 p.id = (
  SELECT p1.id FROM products AS p1
  WHERE c.id=p1.category_id
  ORDER BY p1.id LIMIT 1
 )
Copy after login

This query efficiently retrieves the desired results without encountering nested query issues. Additionally, it outperforms other proposed solutions in terms of execution time, particularly when dealing with large datasets.

The above is the detailed content of How to Retrieve One Product per Category Using JOIN with LIMIT 1?. For more information, please follow other related articles on the PHP Chinese website!

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