gpt4 book ai didi

php - 将这两条 SQL 语句合二为一

转载 作者:可可西里 更新时间:2023-11-01 07:20:33 25 4
gpt4 key购买 nike

将这两个 SQL 语句合并为一个的最佳方法是什么?我尝试使用 union,但似乎无处可去。

select id as id from likes where type=1;

select sum(votes) as votes from likes where parent=id;

这是 likes 表:

id  type  parent  country  votes
1 1 0 US 0
2 2 1 US 6 // This +
19 3 1 US 3 // This
3 3 2 US 3
7 3 2 US 3
4 10 3 US 1
5 10 3 US 1
6 10 3 US 1
10 10 7 US 1
9 10 7 US 1
8 10 7 US 1
20 10 19 US 1
21 10 19 US 1
22 10 19 US 1

这是我想要达到的结果:

id | votes
---------------
1 | 9

最佳答案

试试这个:

SELECT 
l1.id,
SUM(l2.votes) AS Totalvotes
FROM likes AS l1
INNER JOIN likes AS l2 ON l1.id = l2.parent
WHERE l1.type = 1
GROUP BY l1.id;

在此处查看实际效果:

这会给你:

| ID | TOTALVOTES |
-------------------
| 1 | 9 |

关于php - 将这两条 SQL 语句合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16608960/

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