[英]sql - select ids of items in 1st table that have a foreign key for second table by average range
I have a database of a cowshed that have two tables: 我有一个牛棚的数据库,其中有两个表:
Table place_of_cow was created like this: 表place_of_cow的创建如下:
CREATE TABLE place_of_cow (
block_id INT NOT NULL,
cow_id INT NOT NULL,
FOREIGN KEY cow_detailsFK (cow_id)
REFERENCES cow_details (cow_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
);
And the values that i inserted are: 我插入的值是:
INSERT INTO place_of_cow
VALUES (1, 1), (1, 5), (1, 6), (2, 2), (2, 7), (3, 3), (4, 4), (4, 8), (4, 9);
Table cow_details was created like this: 表Cow_details是这样创建的:
CREATE TABLE cow_details (
cow_id INT NOT NULL,
nickname CHAR(25) NOT NULL,
age INT NOT NULL,
CONSTRAINT cow_detailsPK PRIMARY KEY (cow_id)
);
And the values that i inserted are: 我插入的值是:
INSERT INTO cow_details
(cow_id,nickname,age)
VALUES
(1,'hedva',16),
(2,'tali',16),
(3,'cow3',14),
(4,'cow4',9),
(5,'cow5',16),
(6,'cow6',7),
(7,'cow7',4),
(8,'cow8',5),
(9,'cow9',9),
(10,'cow10',7),
(12,'cow12',3),
(13,'cow13',1),
(14,'cow14',1),
(15,'cow15',20),
(16,'cow16',22);
I'm trying to show all the block_ids from table place_of_cow where the average age of the cows in each block_id is above 10 months. 我试图显示表place_of_cow中的所有block_id,其中每个block_id中奶牛的平均年龄都在10个月以上。 I've tried the following code: 我尝试了以下代码:
select distinct p.block_id from place_of_cow as p
where exists
(
select c.cow_id from cow_details as c where c.cow_id = p.cow_id
group by c.cow_id having avg(c.age) > 10
);
but the result is: 但结果是:
block_id: BLOCK_ID:
1 1
2 2
3 3
block_id 2 is not supposed to be in the result. 不应该将block_id 2包含在结果中。 what am i doing wrong? 我究竟做错了什么?
Try this: 尝试这个:
select p.block_id
from place_of_cow p
inner join cow_details d on p.cow_id = d.cow_id
group by p.block_id
having avg(d.age) > 10
You need to group on block_id
, not cow_id
, since the aggregation has to be done with respect to the block, and not the cow. 您需要对block_id
而不是cow_id
,因为必须针对块(而不是母牛)进行聚合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.