我有以下名为tbl_pet_owners的MySQL表:
+----+--------+----------+--------+--------------+
| id | name | pet | city | date_adopted |
+----+--------+----------+--------+--------------+
| 1 | jane | cat | Boston | 2017-07-11 |
| 2 | jane | dog | Boston | 2017-07-11 |
| 3 | jane | cat | Boston | 2017-06-11 |
| 4 | jack | cat | Boston | 2016-07-11 |
| 5 | jim | snake | Boston | 2017-07-11 |
| 6 | jim | goldfish | Boston | 2017-07-11 |
| 7 | joseph | cat | NYC | 2016-07-11 |
| 8 | sam | cat | NYC | 2017-07-11 |
| 9 | drew | dog | NYC | 2016-07-11 |
+----+--------+----------+--------+--------------+
在之前的Stack Overflow帖子中,我使用COUNT寻求帮助以获得每个城市的宠物数量,但如果一个人拥有两个或更多相同类型的宠物,那么这些宠物将被计为一个。宠物类型列在另一个名为tbl_pet_types的MySQL表中:
+----------+-------------+
| pet | type |
+----------+-------------+
| cat | mammal |
| dog | mammal |
| goldfish | fish |
| goldfish | seacreature |
| snake | reptile |
+----------+-------------+
以下是此代码的工作代码:
select count(*), result.city from (
select owners.city, types.type, owners.name
from tbl_pet_owners owners
left join tbl_pet_types types on owners.pet = types.pet group by owners.city, owners.name, types.type
) as result
group by result.city;
我试图修改代码,以便只在2017-01-01'之间采用宠物。和' 2017-08-01'被计算在内。因此,在这个例子中,杰克的猫,约瑟夫的猫和画狗不会被计算在内。
我尝试在我的查询中添加where语句,但是我收到了很多语法错误:
select count(*), result.city from (
select owners.city, types.type, owners.name
from tbl_pet_owners owners
left join tbl_pet_types types on owners.pet = types.pet group by owners.city, owners.name, types.type
) as result where result.date_adopted > '2017-01-01'
and result.date_adopted < '2017-08-01'
group by result.city;
关于如何实现这一目标的任何提示?
答案 0 :(得分:1)
尝试这样的事情:
select count(*), result.city from (
select owners.city, types.type, owners.name
from tbl_pet_owners owners
left join tbl_pet_types types on owners.pet = types.pet
where owners.date_adopted BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'
group by owners.city, owners.name, types.type
) as result
group by result.city;