简体   繁体   English

连接外键表

[英]Joining tables on foreign key

I have the following three tables: 我有以下三个表:

  • Product 产品
  • Purchase (contains ProductID as foreign key) 购买(包含ProductID作为外键)
  • Sale (contain ProductID as foreign key as well) 销售(也包含ProductID作为外键)

I want to form query joining these 3 tables where my result is the product name, purchased, and sold. 我想形成连接这3个表的查询,我的结果是产品名称,购买和出售。

Product Name - (from Products table) Product Name -(来自“产品”表)

Purchased - (Number of occurences in Purchase table according to ProductID) Purchased -(根据ProductID在“购买”表中出现的次数)

Sold - (Number of occurences in Sale Table according to ProductID) Sold -(根据ProductID在销售表中出现的次数)

Can you please set me on the right track by giving me hints and I'll complete by myself? 您能给我一些提示,让我走上正确的道路吗,我会自己完成吗?

I'm betting this will get deleted...but hopefully you see this before it does. 我敢打赌这将被删除...但是希望您能在此之前看到它。 The following is really helpful in understanding the differences in the SQL JOINS. 以下内容对于理解SQL JOINS的区别确实很有帮助。 SQL联接 . This answer or Kyle's answers is all you need to solve your question. 这个答案或Kyle的答案就是解决问题所需要的。

Source: INNER JOIN, LEFT/RIGHT OUTER JOIN 资料来源: INNER JOIN,LEFT / RIGHT OUTER JOIN

As far as a hint, you need to use a join of some sort ( join fundamentals ). 据提示,您需要使用某种连接( join basics )。

A possible answer is below: 可能的答案如下:

Select p.ProductName, pu.Purchased, s.Sold
From Products p 
INNER JOIN Purchase pu on p.ProductID = pu.ProductID
INNER JOIN Sale s on s.ProductID = p.ProductID

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

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