gpt4 book ai didi

mysql - 不知道子select个数时的self join

转载 作者:可可西里 更新时间:2023-11-01 08:03:06 26 4
gpt4 key购买 nike

我有一张表,其中配偶和 child 链接到主要用户。

+----------------+-------------------+----------+------------------------------+------------------+
| Id | User_ID | Rel_Type | Applno | RelationWith |
+----------------+-------------------+----------+------------------------------+------------------+
| 1234756 | aambu ghosha | self | 201708180921 | aambu ghosha |
| 1235146 | parvati ghosha | spouse | NULL | aambu ghosha |
| 1235147 | ananta ghosha | Children | 201708180921 | aambu ghosha |
| 500787 | anant01011975 | self | 20170811171403999L | anant01011975 |
| 501626 | chandu1988 | children | NULL | anant01011975 |
| 1706064 | atmaram sutar | self | 20170821094537517L | atmaram sutar |
| 1706494 | venu sutar | spouse | 20170821094537517L | atmaram sutar |

在上面的例子中,主申请人“aambu ghosha”是“self”(主申请人)。配偶和子女(parvati 和 ananta)需要被视为单一申请人。

aambu ghosha 3
anant01011975 2
atmaram sutar 2

主申请人的人数应该包括他们的家庭成员。预期结果如上所示。我想这可以通过自加入来实现,但我不确定有多少 child 与主申请人相关联。查找计数的最佳方法是什么?

http://sqlfiddle.com/#!9/30945c/2/0


更新:

我如何自助加入并更新与主申请人关联的申请号?例如第二条记录NULL值应改为201708180921。

最佳答案

假设您只有一个级别的 child ,这会起作用

SELECT userid, count(*)
FROM tab p
JOIN tab ch ON p.user_id = ch.RelationWith
WHERE p.user_id = p.RelationWith
GROUP BY userid

实际上,即使是更简单的查询也会产生您请求的结果

SELECT RelationWith, count(*)
FROM tab
GROUP BY RelationWith

关于mysql - 不知道子select个数时的self join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45958879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com