首页 > 解决方案 > 在 SQL 中组合具有不同属性和大小的表

问题描述

我有以下三个表:

Product(manufacturer,model,type)
Laptop(model,speed,ram,hd,price)
Printer (model,color,type,price)

如您所见,产品表包含制造商的名称和他们制造的产品的型号。type 属性只是指定是打印机还是笔记本电脑。 现在假设作为用户,我想查找制造商“A”制造的所有产品(笔记本电脑和打印机),并且输出应该是一张表。 使用 SQL 语句。

我感到困惑的是如何组合具有不同属性和列大小的两个表。截至目前,我刚刚找到制造商“A”的笔记本电脑和个人电脑型号:

SELECT * from Product P , Laptop L where P.model = L.model
SELECT * from Product P, Printer PR where P.model = PR.model

请注意,这是两个单独的查询。我只是不知道如何将它们结合起来。试过UNION但没有帮助

编辑:问题表明我需要打印型号、产品类型以及适合该类型的任何关系的所有属性。

标签: mysqlsql

解决方案


看起来你可以这样做:

select p.*
from product p
where p.manufacturer = 'A' and
      (exists (select 1
               from laptop l
               where l.model = p.model and l.type = 'laptop'
              ) or
       exists (select 1
               from printer pr
               where pr.model = p.model and pr.type = 'printer'
              )
      );

但是,您似乎可以这样做:

select p.*
from product p
where p.type in ('laptop', 'printer');

如果要引入其他属性,请union all像这样使用:

select p.*, lp.*
from product p join
     ((select model, type, price
       from laptop
      ) union all
      (select model, type, price
       from printer
      )
     ) lp
     on lp.model = p.model and lp.type = p.type;

推荐阅读