简体   繁体   English

3个表的SQL求和

[英]Summation from 3 tables SQL

I have 4 tables that carry the following schema: 我有4个表,它们具有以下架构:

  • Product (maker, model, type) 产品 (制造商,型号,类型)
  • PC (model, speed, ram, hd, price) PC (型号,速度,内存,高清,价格)
  • Laptop (model, speed, ram, hd, screen, price) 笔记本电脑 (型号,速度,内存,高清,屏幕,价格)
  • Printer (model, color,type, price) 打印机 (型号,颜色,类型,价格)

Say I need to buy a PC, a Laptop, and a Printer all within a budget of $2K. 假设我需要购买一台PC,一台笔记本电脑和一台打印机,且预算都在2000美元以内。 What query should I use to find all of the available options that are underneath this budget? 我应该使用哪个查询来查找此预算下的所有可用选项?

Obviously for this problem I would need to look at all of the model #'s of PCs, Laptops, and Printers, and filter out the respective prices for each of those products. 显然,对于这个问题,我需要看所有的模型#'s PC,笔记本电脑和打印机,并筛选出各自的价格为每个产品。

But I'm not quite too sure what would be needed in my where clause to do this correctly. 但是我不太确定在where子句中需要什么才能正确执行此操作。

select Product.model
from Product, PC, Laptop, Printer
where ... ???

I would guess you coud to something along these lines to start 我想你会从这些方面开始

Select * 
From PC, Laptop, Printer
Where (PC.price + Laptop.price + Printer.price) <= 2000

The implied join "From PC, Laptop, Printer" would make all the combinations since there not "joining Where", and then you just select the combinations that match you pricing criteria. 隐含的联接“来自PC,笔记本电脑,打印机”将进行所有组合,因为那里没有“联接位置”,然后您只需选择与定价条件匹配的组合即可。

try 尝试

select Product.model
  from Product a, PC b, Laptop c, Printer d
 where a.model = b.model
   and a.model = c.model
   and a.model = d.model
   and b.model = c.model
   and b.model = d.model
   and c.model = d.model

This is a bad query, it is best to separate the query will get better performance 这是一个不好的查询,最好分开查询将获得更好的性能

select PC.Model, PC.Price, Laptop.Model, Laptop.Price, Printer.Model, Printer.Price
from PC, Laptop, Printer
where (PC.price + Laptop.Price + Printer.Price) <= 2000

Does this work for you? 这对您有用吗?

You can try CROSS JOIN or CROSS APPLY to get all the possible combinations and then filter out all that have price sum less than 2K$ 您可以尝试使用CROSS JOIN或CROSS APPLY来获取所有可能的组合,然后滤除价格总和小于2K $的所有组合

Something like 就像是

SELECT
*
FROM PC
CROSS APPLY Laptop
CROSS APPLY Printer
WHERE
PC.price + Laptop.price + Printer.price < 2000

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

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