mysql - mysql中返回主键的嵌套查询?
问题描述
Q. 打印最大客户订购且价格大于 3.0 的产品的完整详细信息
产品
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| productID | int | NO | PRI | NULL | auto_increment |
| Name | varchar(30) | NO | | NULL | |
| Price | double(3,2) | NO | | NULL | |
| CoffeeOrigin | varchar(30) | YES | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
订单
+------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+----------------+
| orderID | int | NO | PRI | NULL | auto_increment |
| productID | int | YES | MUL | NULL | |
| customerID | int | YES | MUL | NULL | |
| Date_Time | DateTime | NO | | NULL | |
+------------+----------+------+-----+---------+----------------+
询问:
select * from products where productID=y.id (
select y.id from (
select products.productsID as id, count(*) as counter
from orders join products on orders.productID=products.productID
group by productID order by counter desc limit 1
) y
);
我在做什么不正确?
解决方案
两件事情:
首先,如果您使用标量子查询,则不需要给它一个表别名y
。如果您将子查询用作派生表,则只需分配表别名。也就是说,在 FROM 子句中。
其次,如果你比较productID
标量子查询的结果,你不需要引用y.ID
. 子查询表达式本身可以是比较的右侧。
您可以编写表达式来与标量子查询进行比较,如下所示:
WHERE productID = ( ... subquery... )
子查询后面没有表别名,也不需要引用y.ID
.
推荐阅读
- python - 如何从 numpy 数组中删除在另一个数组中等于零的所有元素?
- c++ - vector.push_back 增加共享指针计数?
- python-3.x - 如何 Python3 将 CSV 标头导入列表
- macos - 在 macOS 上运行 Comma IDE 时未找到匹配的 VM
- flutter - 根据其在屏幕上的全局位置设置 DecoratedBox 样式
- php - Symfony 5 - 需要信号量扩展(sysvsem)
- youtube - 使用亚马逊服务在 Youtube 上循环直播
- python - 我试图阻止 python 上 os.system('ping') 函数的时间/延迟
- java - 如何为 2 个 HTML 表单使用相同的提交
- node.js - 404 快线