Home > Database > Mysql Tutorial > How to Avoid Duplicate Rows When Joining Multiple Tables in MySQL?

How to Avoid Duplicate Rows When Joining Multiple Tables in MySQL?

Susan Sarandon
Release: 2024-12-06 07:14:14
Original
789 people have browsed it

How to Avoid Duplicate Rows When Joining Multiple Tables in MySQL?

JOIN with Multiple Tables in MySQL

Problem:
When selecting data from multiple tables in MySQL using a simple JOIN without specifying any conditions, it can result in duplicate rows due to multiple rows being joined for each matching key. How can we eliminate these duplicates and retrieve unique rows for each drink, including all associated photos?

Solution:
To resolve this issue, we need to utilize grouping and aggregate functions to combine duplicate rows and select a desired value from them.

Firstly, we group the rows by the drinks_id to obtain only one row for each drink:

SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id
Copy after login

This approach will return one row per drink with only one photo. To include all the associated photos, we can use the GROUP_CONCAT function to concatenate the photo file names into a single string:

SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id
Copy after login

This query will generate a table with unique drink rows and a concatenated string containing all the photo file names for each drink.

Note that GROUP_CONCAT is a MySQL-specific function and may not be supported in other database systems. In such cases, alternative approaches, such as subqueries or array data types, may need to be considered.

The above is the detailed content of How to Avoid Duplicate Rows When Joining Multiple Tables in MySQL?. 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