查询以从不同的行中选择值,并将它们作为列添加到另一个表中

时间:2012-09-05 22:22:20

标签: mysql

我有以下表格:

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

我想在给定family的{​​{1}}中选择一行,并让它返回child_id, mother_id and father_id中的所有列以及与{family相关联的用户名称的3个新列。 1}}

child_id, mother_id and father_id

这可能吗?我最初的名字和家庭表中的id一起,但我觉得重复两个表中的列是多余的。

1 个答案:

答案 0 :(得分: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 = ?