2012-09-05 26 views
0

我有以下表格:查詢,用於選擇不同行的價值觀和他們作爲列添加到另一個表

user {user_id, name} 
family {child_id, mother_id, father_id, address, household_income} 

我想給child_id, mother_id and father_idfamily選擇一行,並讓它返回family所有列與用戶的名字的3分新列隨着child_id, mother_id and father_id

family {child_id, mother_id, father_id, address, 
     household_income, child_name, mother_name, father_name} 

這是可能的關聯?我原本在家庭表中有姓名,但我覺得重複兩張表中的列是多餘的。

回答

1

瞭解有關SQL joins

SELECT family.*, 
     child.name AS child_name, 
     mother.name AS mother_name, 
     father.name AS father_name 
FROM family 
    JOIN user AS child ON child.user_id = family.child_id 
    JOIN user AS mother ON mother.user_id = family.mother_id 
    JOIN user AS father ON father.user_id = family.father_id 
WHERE family.child_id = ? 
    AND family.mother_id = ? 
    AND family.father_id = ? 
相關問題