首页 > 解决方案 > 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
);

我在做什么不正确?

标签: mysqlprimary-key

解决方案


两件事情:

首先,如果您使用标量子查询,则不需要给它一个表别名y。如果您将子查询用作派生表,则只需分配表别名。也就是说,在 FROM 子句中。

其次,如果你比较productID标量子查询的结果,你不需要引用y.ID. 子查询表达式本身可以是比较的右侧。

您可以编写表达式来与标量子查询进行比较,如下所示:

WHERE productID = ( ... subquery... )

子查询后面没有表别名,也不需要引用y.ID.


推荐阅读