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.
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. I would suggest doing this in the FROM
clause:
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. If so, you should drop the 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.