如何通过连接两个表来计数

时间:2016-06-23 08:27:25

标签: mysql sql

我有2张这样的桌子。

表:家庭成员

----------------------------------
|Address                 | Name  |
----------------------------------
|North Jakarta City      | Andra |
|North Jakarta City      | Halim |
|South Jakarta City      | Irma  |
|Thousand Island Village | Dian  |
----------------------------------

表:会员详细信息

---------------
| Name  | Age |
---------------
| Andra | 1   |
| Halim | 50  |
| Irma  | 20  |
| Dian  | 4   |
---------------

如果我想计算一个居住在城市的0到4岁之间的成员,那么正确的查询是什么?我尝试过使用此查询,但结果不正确。正确的结果应该是1,因为只有安德拉住在一个城市和0到4岁之间。请帮助我。

SELECT COUNT(family_members.name) AS total FROM family_members, member_details 
WHERE family_members.address LIKE '%City%' AND member_details.age BETWEEN 0 AND 4

2 个答案:

答案 0 :(得分:4)

您需要加入

SELECT COUNT(fm.name) AS total 
FROM family_members fm
Join member_details md on md.Name = fm.Name
WHERE fm.address LIKE '%City%' AND md.age BETWEEN 0 AND 4

使用语法,您可以在where子句中添加它(因为您的查询将生成cartesian product)。

但是:你应该使用JOIN语法

AND family_members.Name = member_details.Name

修改 顺便说一句,我强烈建议在你的表中使用surrogate keys(名称不是真正独特的)

答案 1 :(得分:0)

您应该考虑重新设计数据库,如:

----------------------------------
| user_id | Name  | Age | city_id |
----------------------------------
|    1    | Andra | 1   |    1    |
|    2    | Halim | 50  |    1    |
|    3    | Irma  | 20  |    1    |
|    4    | Dian  | 4   |    2    |
----------------------------------


------------------------------------
|city_name               | city_id  |
------------------------------------
|North Jakarta City      |    1     |
|Thousand Island Village |    2     |
------------------------------------


SELECT COUNT(*) AS total 
FROM family_member
JOIN city on family_member.city_id = city.city_id
WHERE city.city_name= 'City' AND family_member.age BETWEEN 0 AND 4;

您还应该添加索引。