mysql - 在 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
但没有帮助
编辑:问题表明我需要打印型号、产品类型以及适合该类型的任何关系的所有属性。
解决方案
看起来你可以这样做:
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;
推荐阅读
- sql - SQL 查询中的 ANY 和 ALL 运算符
- java - 无法弄清楚为什么矩阵 a 双打
- pine-script - pinescript 尾随停止在第一个之后不起作用
- docker - 为基于 WSL 的 ubuntu 20.04 设置 docker 时出现问题。我想确保 WSL2 深度学习可以使用我的 GPU
- javascript - 为什么其他 javaScript 函数无法读取用 javaScript 制作的 div?
- reactjs - 在单元测试中安装时,FormattedTime 组件抛出错误
- javascript - document.querySelectorAll() 不适用于额外 div 中的同一类
- php - Illuminate\Contracts\Container\BindingResolutionException,目标类 [admincontrol] 不存在
- c - 如何打印动态数组的所有元素?并找到最小值
- javascript - 我的 Vue 组件没有出现在 Laravel 中