简体   繁体   English

sql内部联接不适用于内部联接

[英]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 我有客户,物品,制造,订单,库存等表格。请参阅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 . 我想获得订购了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 我得到了8条正确的记录,我进一步希望从stock表获得这些记录的描述,因此我在stock表上创建了一个联接

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. 现在,它给了我24条我没想到的记录。 How do I write a nested query to get only 8 records? 如何编写嵌套查询以仅获取8条记录?

Stock schema enter image description here 库存模式在此处输入图像描述

You have 24 stock items from the manufacturer. 您有24个制造商的库存商品。 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 : 您还省略了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. 我还怀疑stock有一些您也应该加入的itemid

You can see from your stock table that, there are multiple stock_num for a manu_code . 你可以从你的股票表看到,有多个stock_nummanu_code There are 3 stock_num for the corresponding manu_code for m.manu_name = 'Smith' m.manu_name = 'Smith'对应的manu_code有3个stock_num

Thats why your query returns 8*3 = 24 rows. 这就是为什么您的查询返回8 * 3 = 24行的原因。

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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