简体   繁体   English

如何在第三个变量mysql查询中求和两个子查询的总和?

[英]How to sum two subqueries count in third variable mysql query?

I am trying to sum total likes and comments but result is always zero (0) please help me to resolve this issue because i have implemented mostly solutions that I find but no success. 我正在尝试汇总喜欢和评论的总数,但结果始终为零(0),因为我已经实施了大部分发现但没有成功的解决方案,请帮助我解决此问题。

SELECT DISTINCT id,name,picture,
(SELECT COUNT(id) from likes) as likes,
(SELECT COUNT(id) from comments) as comments,
(likes+comments) as total
From users

You cannot use column aliases in the same SELECT where they are defined. 您不能在定义它们的同一SELECT中使用列别名。 I would suggest doing this in the FROM clause: 我建议在FROM子句中这样做:

SELECT DISTINCT u.id, u.name, u.picture, l.likes, c.comments,
       (l.likes + c.comments) as total
FROM users u CROSS JOIN
     (SELECT COUNT(id) as likes FROM likes) l CROSS JOIN
     (SELECT COUNT(id) as comments FROM comments) c;

Presumably, u.id is unique. 大概u.id是唯一的。 If so, you should drop the SELECT DISTINCT . 如果是这样,则应删除SELECT DISTINCT It just adversely affects performance. 它只会对性能产生不利影响。

You can try like this 你可以这样尝试

SELECT DISTINCT id,name,picture,
(SELECT COUNT(id) from likes) as likes,
(SELECT COUNT(id) from comments) as comments,
(SELECT COUNT(id) from likes)+(SELECT COUNT(id) from comments) as total
From users

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

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