gpt4 book ai didi

mysql - 多个子查询,计算更多儿子但有条件

转载 作者:行者123 更新时间:2023-11-29 15:21:10 26 4
gpt4 key购买 nike


你好!这工作正常,但我需要计算更多的儿子,但有一个条件

select t1.*,(select count(*)
from tabl t2
where t2.tabl = t1.id) as sons
from tabl t1 where tabl.sons = ?;

我尝试了这个,但收到以下错误...

SQL ERROR: Operand should contain 1 column(s)

 select t1.*,(select count(*),(select count(*) from tbl1 t3 where t3.type = 3) as Johnny
from tabl t2
where t2.tabl = t1.id) as sons
from tabl t1 where tabl.sons = ?;

请,谢谢

编辑:这正是我想要的,但我认为这不是正确的方法(对不起,我改了名字,但看起来更好了)

select m1.*,
(select count(*) from node m2 where m2.nodeid = m1.id) as child,
(select count(*) from node m3 where m3.type = 3 and m3.nodeid = m1.id) as del,
(select count(*) from node m3 where m3.type = 1 and m3.nodeid = m1.id) as edit,
(select count(*) from node m3 where m3.type = 4 and m3.nodeid = m1.id) as protect,
(select count(*) from node m3 where m3.type = 2 and m3.nodeid = m1.id) as move
from node m1 where nodeid = ?
+----+--------+------+-------+------+------+---------+------+
| id | nodeid | type | child | del | edit | protect | move |
+----+--------+------+-------+------+------+---------+------+
| 1 | null | 0 | 3 | 0 | 1 | 1 | 1 |
+----+--------+------+-------+------+------+---------+------+

+----+--------+------+-------+------+------+---------+------+
| id | nodeid | type | child | del | edit | protect | move |
+----+--------+------+-------+------+------+---------+------+
| 34 | 1 | 1 | 7 | 2 | 1 | 1 | 1 |
| 23 | 1 | 2 | 3 | 1 | 0 | 0 | 0 |
| 32 | 1 | 3 | 2 | 0 | 0 | 0 | 0 |
+----+--------+------+-------+------+------+---------+------+

基本上有多少个 child 以及每种类型有多少个xd

最佳答案

MySQL 8 有了窗口函数。因此,您可以在其中编写查询,如下所示:

SELECT t1.*, COUNT(*) OVER(PARTITION BY t1.id ORDER BY t1.id) AS sons,
COUNT(CASE WHEN t1.type = 3 THEN t1.type END) OVER (PARTITION BY t1.id ORDER BY t1.id) AS Johnny
FROM tabl t1
WHERE t1.sons = ?;

关于mysql - 多个子查询,计算更多儿子但有条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59369770/

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