简体   繁体   中英

sql inner join not working for inner join

I have tables like customer, items, manufacture, order, stock.. refer http://www.oninit.com/manual/informix/english/docs/gn7382/4366.pdf

I want to get the first and last names of every person (and the city and state they live in) who has ordered something made by the company Smith . Include the description (from the stock table).

If I execute the first part as

select c.fname, c.lname, c.city, c.state from customer c join orders o using (customer_num)
join items i using(order_num)
join manufact m using(manu_code)  where m.manu_name = 'Smith' ;

I get 8 records which is correct, I further want the description from stock table for these records, so I created a join on stock table like

select c.fname, c.lname, c.city, c.state, s.description from customer c join orders o using (customer_num)
join items i using(order_num)
left join (manufact m join stock s on m.manu_code=s.manu_code) on m.manu_code = i.manu_code where m.manu_name = 'Smith';

Now, its giving me 24 records which I dont expect. How do I write a nested query to get only 8 records?

Stock schema enter image description here

You have 24 stock items from the manufacturer. You need to decide what you want to display.

Your query is doing what you want it to do.

I would say, though, that structuring the query without the nested join is simpler. You also left out the description :

select c.fname, c.lname, c.city, c.state, s.description
from customer c join
     orders o
     using (customer_num) join
     items i
     using (order_num) join
     manufact m
     using (manu_code) join
     stock s
     using (manu_code)
where m.manu_name = 'Smith';

I also suspect that stock has some sort of itemid that you should also be joining on.

You can see from your stock table that, there are multiple stock_num for a manu_code . There are 3 stock_num for the corresponding manu_code for m.manu_name = 'Smith'

Thats why your query returns 8*3 = 24 rows.

To get the appropriate result, you can

select c.fname, c.lname, c.city, c.state, s.description
from customer c 
     join orders o using (customer_num) 
     join items i using (order_num) 
     join manufact m using (manu_code) 
     join (select description from stock group by manu_code) AS s ON s.manu_code = m.manu_code
where m.manu_name = 'Smith'

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