繁体   English   中英

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

[英]Query to select values from different rows and add them as columns to another table

我有以下表格:

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

我想在给定child_id, mother_id and father_id family选择一行,并使其返回family所有列以及与child_id, mother_id and father_id相关的用户名的3个新列

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

这可能吗? 我最初在族表中具有名称和ID,但是我觉得在两个表中重复列是多余的。

了解有关SQL连接的信息

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 = ?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM