[英]MYSQL error in 'unknown column in having clause'
查询如下,我得到错误:
SELECT a.name
FROM author a, catalog c
WHERE a.authorid = c.authorid
AND c.bookid IN (
SELECT bookid
FROM orderdetails
GROUP BY bookid
HAVING sum(quantity) = (
SELECT max(sum(quantity))
FROM orderdetails
)
);
下表由书店维护。
AUTHOR (author-id:int, name:string, city:string, country:string)
PUBLISHER (publisher-id:int, name:string, city:string, country:string)
CATALOG (book-id:int, title:string, author-id:int, publisher-id:int, category-id:int, year:int, price:int)
CATEGORY (category-id:int, description:string)
ORDER-DETAILS (order-no:int, book-id:int, quantity:int)
问题是:
iv。 查找销量最高的书的作者。
可能是您需要一个中间小组
select a.name
from author a
inner join catalog c on a.authorid=c.authorid
and c.bookid in (select bookid
from orderdetails
group by bookid
having sum(quantity) = (
select max( sum_quantity) from (
select sum(quantity) sum_quantity
from orderdetails
group by bookid
)
);
您会收到错误消息,因为仅在您选择的列上具有:
SELECT a.name
FROM author a, catalog c
WHERE a.authorid = c.authorid
AND c.bookid IN (
SELECT bookid, sum(quantity) as total_qty
FROM orderdetails
GROUP BY bookid
HAVING total_qty = (
SELECT max(sum(quantity))
FROM orderdetails
)
);
我认为您可以避免使用IN,最好尝试减少查询量:
SELECT a.name
FROM author a
INNER JOIN catalog c ON a.authorid = c.authorid
INNER JOIN (
SELECT bookid, sum(quantity) as total_qty
FROM orderdetails
GROUP BY bookid
HAVING total_qty = (
SELECT max(sum(quantity))
FROM orderdetails
)
) t ON t.bookid = c.bookid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.