2017-07-27 96 views
1

我想總結喜歡和評論,但結果總是爲零(0) 請幫我解決這個問題,因爲我已經實現了大部分我找到但沒有成功的解決方案。如何總結兩個子查詢計數在第三個變量mysql查詢?

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

你需要加入的喜好和意見表的用戶表來做到這一點。你能提供關於你的表格結構的更多細節嗎? – 83N

+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。這隻會對性能產生不利影響。

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