我正在进行sql查询的练习,但是到了我有3个同名的列,其中一些包含null,这是什么选项,所以我可以将它们组合成一个列调用价格而不是3
Short database description "Computer firm":
The database scheme consists of four tables:
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price)
Printer(code, model, color, type, price)
“产品”表包含有关制造商,型号和类型(“PC”,“笔记本电脑”或“打印机”)的信息。假设Product表中的型号对于所有制造商和产品类型都是唯一的。通过表“PC”中的代码唯一指定的每台PC的特征在于型号(引用产品表的外键),速度(处理器的速度,以MHz为单位),RAM总量 - RAM(以Mb为单位),硬盘驱动器容量 - 高清(在Gb中),CD ROM速度 - cd(例如,'4x')和价格。表“笔记本电脑”类似于PC之一,除了CD ROM速度,它被屏幕尺寸 - 屏幕(以英寸为单位)取代。对于“打印机”表中的每台打印机,都会告知打印机是否为彩色(彩色打印机的颜色属性为'y';否则为'n'),打印机类型(激光,喷墨或矩阵),以及价格
练习:7 找出制造商B生产的所有产品(任何类型)的型号和价格。
我的疑问:
SELECT distinct Product.model, PC.price, Laptop.price,Printer.price as price
from Product
left join PC
on Product.model=PC.model
left JOIN Laptop
ON Product.model=Laptop.model
left join Printer
on Product.model= Printer.model
where Product.maker='B';
输出:
您的查询:
model price price price
1121 850 NULL NULL
1750 NULL 1200 NULL
正确查询:
model price
1121 850
1750 1200
答案 0 :(得分:2)
尝试使用COALESCE
SELECT distinct Product.model,
COALESCE(PC.price, Laptop.price,Printer.price) as price
from Product left join PC
on Product.model = PC.model
left JOIN Laptop
ON Product.model = Laptop.model
left join Printer
on Product.model = Printer.model
where Product.maker='B'
来自定义,
COALESCE Returns the first nonnull expression among its arguments.
更新1
SELECT a.model, a.price
FROM PC a INNER JOIN Product b
ON a.model = b.model
WHERE b.maker = 'makerB'
UNION
SELECT a.model, a.price
FROM Laptop a INNER JOIN Product b
ON a.model = b.model
WHERE b.maker = 'makerB'
UNION
SELECT a.model, a.price
FROM Printer a INNER JOIN Product b
ON a.model = b.model
WHERE b.maker = 'makerB'
答案 1 :(得分:0)
您可以使用UNION
SELECT Product.model, newTbl.price FROM Product
INNER JOIN
(
SELECT model, price FROM PC
UNION
SELECT model, price FROM Laptop
UNION
SELECT model, price FROM Printer
)newTbl ON Product.model = newTbl.model
或者如果您只需要表格 model 的产品中的1列,您可以像这样放弃产品表
SELECT model, price FROM PC
UNION
SELECT model, price FROM Laptop
UNION
SELECT model, price FROM Printer
答案 2 :(得分:-1)
SELECT AVG( price) FROM (
SELECT price, model
FROM pc
WHERE model IN (
SELECT model
FROM product
WHERE maker='A' AND type='PC'
)
UNION ALL
SELECT price, model
FROM laptop
WHERE model IN (
SELECT model
FROM product
WHERE maker='A' AND type='Laptop'
)
) as prod