2016-06-23 58 views
1

我有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 
+0

'FROM family_members加入member_details使用(名稱)' – splash58

回答

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(名字是真的不是唯一的)

+0

謝謝它的作品:) –

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; 

還y你應該添加索引。

相關問題