r/learnSQL • • 1d ago

Confusion about joining tables.

can anyone help me to understand how one to many relation tables work .how to avoid duplicates when joining.i am struggling to understand how it works

8 Upvotes

16 comments sorted by

4

u/markinatlanta 1d ago

So imagine one customer with three orders. Joining customers to orders gives you three rows, with the customer’s name repeated. Those aren’t duplicates... each row represents a different order.

The question is what you want one row to represent:

  • Each order: keep all three rows.
  • Each customer with their total spend: aggregate the orders per customer, then join.
  • Each customer who has any orders: use EXISTS.

Don’t reach for DISTINCT until you understand why the extra rows appeared.

1

u/atrifleamused 1d ago

Top tip there!

1

u/markinatlanta 9h ago

thank you sir!

6

u/squadette23 1d ago

You may be interested in "A modern guide to SQL JOINs": https://kb.databasedesignbook.com/posts/sql-joins/

The question of overcounting is covered in "Understanding the problem of overcounting".

2

u/DanDaMan1973 1d ago

That is a wonderful read on Joins.

3

u/secret_o_squirrel 1d ago edited 1d ago

A JOIN doesn't pair up rows. It finds every possible match.

Two tiny tables:

A

idquantity
15
25

B

idquantity
15
25
SELECT A.id, B.id
FROM A
JOIN B ON A.quantity = B.quantity;

Result: 4 rows

A.idB.id
11
12
21
22

Why four rows instead of two? Because each row in A matches both rows in B. SQL doesn't pair them off one at a time. It finds every possible pair that follows your rule.

Now change just one thing:

SELECT A.id, B.id
FROM A
JOIN B ON A.id = B.id;

Result: 2 rows

A.idB.id
11
22

Same tables, same JOIN. The only difference is what you told SQL counts as a match.

2

u/m1L35dY50N 1d ago

One important thing to understand about SQL JOINs is that what looks like duplicate rows usually isn't actually a duplicate.

Most of the time, you're seeing multiple records that share the same values in certain columns but have different primary keys or IDs.

A JOIN is basically a way of combining rows from two tables (sets A and B), depending on which matching or non-matching records you want to retrieve.

The easiest way to understand the different JOIN types is to imagine two overlapping circles, A and B, like a Venn diagram.

  • INNER JOIN: Returns only matching combinations of rows from both A and B. Basically, the intersection of both sets.
  • LEFT JOIN: Returns everything from table A, including matching records from B. If there's no match in B, its columns contain NULL.
  • RIGHT JOIN: The opposite of LEFT JOIN. Returns everything from table B, including matching records from A. Unmatched columns from A contain NULL.
  • FULL OUTER JOIN: Returns everything from both tables, including matching and non-matching records. Unmatched columns are filled with NULL. Important: This is different from returning only the records that don't match.
  • ANTI JOIN: Returns records from one table that have no matching records in the other. For example, a LEFT ANTI JOIN returns rows from A that don't exist in B. In MSSQL, you typically implement this using NOT EXISTS or LEFT JOIN ... WHERE B.ID IS NULL.
  • CROSS JOIN: Returns every possible combination of rows from both tables, regardless of whether they match. If A contains 10 rows and B contains 20, the result contains 200 rows.

If you experience "dupes" you maybe have to reconsider if you are using the right join type, the right key to join on, and the usage of the distinct keyword for only display uniques to that given column.

2

u/elevarq 1d ago

Rule number one: there are no duplicates!

You might ask the wrong question and the answer looks like you got duplicates, but it’s exactly what you asked for.

2

u/MerryWalrus 1d ago

A join is just a rule.

If these two rows share some value in some columns, then put them side by side.

Now just think about what happens to that rule of there are multiple copies of the same value in the first, second, or both tables.

Inner, outer, left, right is just instructions on what to do with the records that don't have a matching value.

Of it's a one to many relationship, then there are literally duplicates by definition. What you can do to resolve that is to transpose some columns until it becomes 1-1, or filtering it if you know exactly what the 1-1 join should be.

2

u/nicopassaglia 1d ago

Those aren't really duplicates, and seeing why is most of the answer.

One-to-many means one row on one side matches several on the other: one customer, many orders. A join returns one row per match, so a customer with 3 orders shows up 3 times, once next to each order. Nothing is wrong: the result is a list of orders with the customer's details copied onto each.

So the question to ask before writing the query is "what should one row of my result be?"

- One row per order: the repeats are correct, leave them.

- One row per customer: aggregate. GROUP BY the customer and use COUNT, SUM, MAX on the order columns.

- Just counting customers after a join: COUNT(DISTINCT customer_id), because COUNT(*) counts orders.

The case that really hurts is joining two "many" tables to the same parent, say orders and payments both joined to customers. A customer with 3 orders and 2 payments gives 6 rows, and every SUM comes out too big. The fix is to aggregate each table first in a subquery or CTE (one row per customer), then join those.

Avoid reaching for SELECT DISTINCT to make repeats disappear. It hides the problem and your sums stay wrong.

Disclosure: I built a free page on exactly this, with two small tables and queries you can edit and run in the browser, including the "why did my count come out wrong after the join" one: https://getsheetdrill.com/sql/reference/joins

1

u/ravan363 1d ago

You can think of one to many relationship like.. Users and their orders at a store. There are a cohort of users who shop at the store, they can make multiple transactions at the same store. For ex, a user Mike made 10 transactions last month. If you are pulling this data, the user name would be Mike repeating in 10 rows, on the other side there would be 10 distinct transactions and the transactions details would be there in the table.

1

u/DataFracking 1d ago

owner table and pet table. Bob has two pets, Fido and Chewy. That's one-to-many: one owner, many pets. When you join the two tables, you get one row per pet, so Bob's name shows up twice, on each row for his pet's names. That's expected, not a duplicate. If you want just one row for Bob, group by name and count the pets. You'll get one row: Bob, 2.

1

u/DanDaMan1973 1d ago

I wanna start by saying thank you for these amazing sites that you guys have developed. For those of us who are learning SQL and specifically joins, they are wonderful. I did have an epiphany and I want to know if my thought is correct. I think what was messing me up before was that I had the idea that what you were looking for had to be what joined meaning if you were looking for the customer name and zip code then one of these fields had to join the two tables, but that doesn’t appear to be necessarily true. Is that correct?

1

u/peakpirate007 1d ago

been building https://www.runtime.school/ for learning and practicing sql in one place. lessons, practice, projects and a few tools all use the same datasets, so it feels more connected than jumping between random examples. if you’re learning sql, might be useful.

1

u/datadriven_io 2h ago

The relation table would only have one row for each time a user favorites a movie. Datadriven.io covers data modeling practice problems for anyone prepping on their own. Just add a row that says userid 354 and movieID 234532. That's all you need. To avoid the duplicates delete that row.

0

u/xaomaw 1d ago edited 1d ago
  • Table A customer contains customer data (e.g. adresses). A customer has only 1 adress.
  • Table B cities contains the city_zip_code and the city_name

=> ONE customer can have ONE zip_code (name + zip_code in the same table)

=> ONE zip_code can be used by MULTIPLE customers (1:N join customer.customer_zip_code = cities.city_zip_code)

[🔑 PK] customer_idcustomer_name[🔑 FK] customer_zip_code
1John Smith🟩 70173
2Jane Miller🟩 70173
3Peter Brown🔵 80331
[🔑 PK] city_zip_codecity_name
🟩 70173Stuttgart
🔵 80331Munich

🟩 ONE in the city to MANY in the customer