我想总计喜欢和评论,但结果总是为零(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
答案 0 :(得分:2)
您不能在定义它们的同一SELECT
中使用列别名。我建议在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;
据推测,u.id
是独一无二的。如果是这样,您应该删除SELECT DISTINCT
。它只会对性能产生负面影响。
答案 1 :(得分:0)
您可以尝试这样
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