使用MySQL的COUNT和两个表

时间:2017-07-06 16:26:43

标签: mysql sql

我有以下名为tbl_pet_owners的MySQL表:

+--------+----------+--------+
| name   | pet      | city   |
+========+==========+========+
| jane   | cat      | Boston |
+--------+----------+--------+
| jane   | dog      | Boston |
+--------+----------+--------+
| jack   | cat      | Boston |
+--------+----------+--------+
| jim    | snake    | Boston |
+--------+----------+--------+
| jim    | goldfish | Boston |
+--------+----------+--------+
| joseph | cat      | NYC    |
+--------+----------+--------+

我想使用COUNT来获取每个城市的宠物数量,但如果一个人拥有两个或更多相同类型的宠物,那么这些宠物将被计为一个。宠物类型列在另一个名为tbl_pet_types的MySQL表中:

+----------+---------+
| pet      | type    |
+==========+=========+
| cat      | mammal  |
+----------+---------+
| dog      | mammal  |
+----------+---------+
| snake    | reptile |
+----------+---------+
| goldfish | fish    |
+----------+---------+

因此,由于简的猫与狗属于同一类型,所以它们被认为是一只宠物。 在此示例中,结果为:

Boston 4
NYC    1

有关如何实现这一目标的任何提示?

3 个答案:

答案 0 :(得分:2)

看看是否有效。

SELECT PO.city, COUNT(DISTINCT PO.name, PT.type) 
FROM tbl_pet_owners PO
JOIN tbl_pet_types PT ON PO.pet = PT.pet 
GROUP BY PO.city

答案 1 :(得分:0)

SELECT o.city, COUNT(DISTINCT o.name, t.type)
FROM tbl_pet_owners o, tbl_pet_types t
WHERE o.pet = t.pet
GROUP BY city

答案 2 :(得分:0)

它可以进行优化,但有效:

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;