我有几行代表person
.每个person
都有一列bio_mother _uuid
和bio_father_uuid
.我使用this page(我提到这个是因为它在this similar question中被引用)来实现这个连接.
SELECT
base.uuid base_uuid, base.created_at base_created_at, base.givenname base_givenname, base.bio_mother_uuid base_bio_mother_uuid, base.bio_father_uuid base_bio_father_uuid,
mother.uuid mother_uuid, mother.created_at mother_created_at, mother.givenname mother_givenname, mother.bio_mother_uuid mother_bio_mother_uuid, mother.bio_father_uuid mother_bio_father_uuid,
father.uuid father_uuid, father.created_at father_created_at, father.givenname father_givenname, father.bio_mother_uuid father_bio_mother_uuid, father.bio_father_uuid father_bio_father_uuid
FROM person AS base
LEFT JOIN person AS mother ON base.bio_mother_uuid = mother.uuid
LEFT JOIN person as father ON base.bio_father_uuid = father.uuid;
我希望将行解封到这个Go struct 中
type Person struct{
UUID string
Givenname string
Bio_mother *Person
}
如果我使用上面的查询查询,我会 for each 没有母亲或父亲数据的人获得NULL(这很好),但是当构建母亲/父亲数据时,我最终构建了Person
个不完整的实例,因为我在查询中没有"祖父母"数据.我可以通过在代码中实现逻辑来解决这个问题,以再次查询是否存在UICC,但这比在查询中以某种方式这样做会大大降低程序的速度.
这对我来说是一个学习项目,但我不完全确定谷歌什么来一个好的答案.
我如何调整我的查询来处理我的用例并只在一行中返回?这将与递归CTE有关,但我不完全确定如何在查看了一些PostgreSQL教程之后实现它,
编辑: 我意识到丢失数据意味着必须动态命名这些列,或者可能是一些代码?或者是添加前缀?在这个例子中,我只使用"alias".注意Gertrude是如何丢失母数据的,行上有一个间隙.这是因为模式一直是母亲第一,不确定我是否同意模式的建模是有意义的,但这是我现在可以为这些数据想出的模型.如果我朝错误的方向射击,请告诉我
(为了可读性,我还在前几次迭代后将列缩短为"其他东西",我正在乘坐没有WiFi的火车,所以想把这个问题准备好并关闭)
Example Input and Output
示例数据
uuid | givenname | surname | bio_mother_uuid | bio_father_uuid |
---|---|---|---|---|
aa | david | smith | ab | ac |
ab | mary | smith | ad | ae |
ac | john | smith | af | ag |
ad | gertude | snow | ah | |
ae | Richard | snow | ||
af | Katie | smith | ||
ag | Mathew | smith | ||
ah | Winston | Snow |
期望输出
base_uuid | base_givenname | base_surname | base_bio_mother_uuid | base_bio_father_uuid | mother_uuid | mother_givenname | mother_surname | mother_bio_mother_uuid | mother_bio_father_uuid | father_uuid | father_otherstuff | alias_uuid | alias_otherstuff | alias_uuid | alias_otherstuff | alias_uuid | alias_otherstuff | alias_uuid | alias_otherstuff | alias_uuid | alias_otherstuff | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aa | david | smith | ab | ac | ab | mary | smith | ad | ae | ac | john smith.. | ad | gertrude snow | ae | richard snow | af | katie smith | ag | mathew smith | winston snow | ||
ab | mary | smith | ad | ae | ad | gertrude | snow | ah | ae | richard snow | ah | winston snow |