[英]Column 'City.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
[英]Column 'seller.seller_Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
我正在创建一个 SQL 查询,但遇到了聚合 function 或 group by 子句的一些问题。 我以前从未使用过堆栈溢出,所以请原谅我糟糕的格式和语法。 这些是下面的代码。
**/创建表卖家/
create table seller60 (
seller_ID int identity (1000,1) not null,
seller_Name varchar(100) not null,
seller_userName varchar (100) unique,
seller_password varchar (100) not null,
item_ID int not null,
contactID int not null,
creditCardID int not null,
primary key(seller_ID), foreign key(contactID) references contactInfo(contact_ID),foreign key(creditCardID) references creditCard60(creditCard_ID)
);
**/创建表项/
create table item60(
itemID int identity(1000,1) not null,
itemName varchar(100) not null,
itemDesc varchar (100),
item_initialPrice money,
item_Quantity int,
ownerID int not null,
condition varchar(100) not null,
primary key( itemID), foreign key(ownerID) references seller60(seller_ID)
);
**/最活跃的卖家/
SELECT a.ownerID, b.seller_Name
FROM item AS a
INNER JOIN seller AS b ON a.ownerID = b.seller_ID
GROUP BY a.ownerID
ORDER BY COUNT(a.itemID) DESC set rowcount 1;
这里的问题是select
子句与group by
子句不一致:您在select
子句中有非聚合列seller60(seller_name)
,但不在group by
子句中,并且 Z62A4104B9594673AZ
一种方法是将该列添加到group by
子句。 一个更聪明的选择是按列seller60(seller_id)
:这与item(owner_id)
相同(即该列的外键); 并且,由于这是seller60
的主键,因此您可以在select
子句中添加任意数量的列,而不会破坏查询(这是功能相关列的概念,MySQL 理解)。
select s.*
from item60 i
inner join seller60 s on i.ownerid = s.seller_id
group by s.seller_id
order by count(*) desc limit 1;
请注意,这使用有意义的表别名,而不是随机字母,例如a
或b
。 我还修复了语法关闭的limit
子句。
最后:您也可以使用相关子查询获得相同的结果 - 然后您根本不需要担心聚合。
select s.*
from seller60 s
order by (select count(*) from item60 i where i.ownerid = s.seller_id) desc limit 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.