简体   繁体   中英

SQL Join involving 3 tables, how to?

SQL newbie here.

So we have 3 tables:

categories(cat_id,name);   
products(prod_id,name);
relationships(prod_id,cat_id); 

It is a one-to-many relationship.

So, given a category name say "Books". How do I find all the products that come under books?

As an example,

categories(1,Books);  
categories(2,Phones);  
products(302,Sherlock Holmes);  
relationships(302,1);  

You need to JOIN the three tables.

SELECT  p.*
FROM relationships r
INNER JOIN products p
    ON p.prod_id = r.prod_id
INNER JOIN categories c
    ON c.cat_d = r.cat_id
WHERE c.name = 'Books'

You have to join tables on related columns and specify WHERE clause to select all records where category name = 'Books'

SELECT p.*
FROM categories c
JOIN relationships r ON c.cat_id = r.cat_id
JOIN products p ON r.prod_id = p.prod_id
WHERE c.name = 'Books' -- or specify parameter like @Books

In SQL you often join related tables and beginners tend to join, whatever the situation. I would not recommend this. In your case you want to select products. If you only want to show products data, select from products only. You want to select products that are in the category 'Books' (or for which exists an entry in category 'Books'). Hence use an IN or EXISTS clause in order to find them:

select * from products
where prod_id in
(
  select prod_id
  from relationships
  where cat_id = (select cat_id from categories where name = 'Books')
);

Thus you get a well structured query that tells the reader easily how the tables are related and what data you are actually interested in. Later, with different tables and data to select, this may keep you from duplicate result rows that you must get rid of by using DISTINCT or from getting wrong aggregates (sums, counts, etc.), because of mistakenly considering records multifold.

try this:

select p.Prod_id,p.name 
from products p inner join relationships r on 
p.prod_id = r.prod_id
where r.cat_id = (select cat_id from categories where name = 'books')

or

select p.Prod_id,p.name 
from products p inner join relationships r on 
p.prod_id = r.prod_id inner join categories c on c.cat_id = r.cat_id
where c.name = 'books'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM