mysql - 给定情况下的 SQL 查询优化
问题描述
这些是给定的表格:
create table products
(productID int not null auto_increment,
Name varchar(30),
Price float ,
CoffeOrigin varchar(30),
primary key (productID));
create table customers
(customerID int not null auto_increment,
First_Name varchar(30),
Last_Name varchar(30),
Gender varchar(2) not null CHECK (Gender IN ('M', 'F')),
ContactNumber bigint,
primary key (customerID));
create table orders
(orderID int not null auto_increment,
productID int,
customerID int,
Date_Time datetime,
primary key(orderID),
foreign key(customerID) references customers(customerID),
foreign key(productID) references products(productID));
问题是:
编写优化查询以找出所有订购咖啡的客户 ID 的名称,这些咖啡源自“哥斯达黎加”或“印度尼西亚”。
我的尝试:
select customers.customerID, first_name, last_name from customers where customerID in
(select customerID from orders where productid in
(select productid from products where coffeorigin = "costa rica" or "indonesia"));
我的老师说它可以进一步优化,但我看不到任何方法。请帮帮我。
解决方案
而不是这些嵌套的in
子查询,我会推荐exists
一个相关的子查询join
:
select c.customerID, c.first_name, c.last_name
from customers c
where exists (
select 1
from orders o
inner join products p on p.productID = o.productID
where p.coffeorigin in ('costa rica', 'indonesia') and o.customerID = c.customerID
);
推荐阅读
- docker - Docker Compose 与 MacOS Docker Desktop 观察变化
- php - xampp curl 无法解析主机
- microsoft-graph-api - Microsoft Graph - FindMeetingTimes API 错误?
- asp.net - 创建一个过滤我的转发器输出的下拉列表
- if-statement - 报告生成器 - 如何使用 if 语句?
- django - 如何在 Django 中显示继承模型的字段?
- html - 我怎样才能拥有一张响应迅速且不破坏文字的表格?
- sqlalchemy - SqlAlchemy - 在关系属性是列表的情况下进行查询
- postgresql - 如何在 Postgres 容器中插入存储的函数和触发器
- c# - Linq2DB T4 代码生成缺少 SQLite.Interop.dll