1

我正在做 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”、“笔记本电脑”或“打印机”)的信息。假定产品表中的型号对于所有制造商和产品类型都是唯一的。由表“PC”中的代码唯一指定的每台 PC 的特征在于型号(参考产品表的外键)、速度(处理器的 MHz)、RAM 总量 - ram(以 Mb 为单位)、硬盘驱动器容量- hd(以 Gb 为单位)、CD ROM 速度 - cd(例如,'4x')和价格。表“笔记本电脑”类似于 PC 之一,除了 CD ROM 速度,它被屏幕尺寸 - 屏幕(英寸)取代。对于“打印机”表中的每台打印机,它都被告知打印机是否是彩色的(彩色打印机的颜色属性为“y”;

练习: 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
4

3 回答 3

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'
于 2012-12-13T06:28:46.487 回答
0

您可以使用联合

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

或者如果您只需要模型表 Product 中的 1 列,您可以像这样丢弃 Product 表

SELECT model, price FROM PC
      UNION
SELECT model, price FROM Laptop
      UNION
SELECT model, price FROM Printer
于 2012-12-13T06:41:43.737 回答
-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
于 2014-04-30T11:05:36.007 回答