3

我想使用MySql将多个表的结果计数与列明智的结果结合起来(请参阅所需的结果),但如果您对此有任何查询或优化方式,我对此感到困惑,请回答我或帮助,我也试过了我自己这个查询联合但严重不成功(请参阅查询示例

需要结果

post  post_comment_likes  post_comments  post_likes
2     0                   3              0

询问

SELECT COUNT(*) AS `post` FROM post WHERE user_id = "123456" UNION
SELECT COUNT(*) AS `post_comment_likes` FROM post_comment_likes WHERE user_id = "123456" UNION 
SELECT COUNT(*) AS `post_comments` FROM post_comments WHERE user_id = "123456" UNION
SELECT COUNT(*) AS `post_likes` FROM post_likes WHERE user_id = "123456" 
4

3 回答 3

1
set @post = 0;
set @post_comment_likes = 0;
set @post_comments = 0;
Set @post_likes = 0;


 select count(*) into @post from .......;
 select count(*) into @post_comment_likes from ......;
 select count(*) into @post_comments from ......;
 select count(*) into @post_likes from ......;

select (@post + @post_comment_likes + @post_comments + @post_likes) ;

在上面的代码中 @post 、 @post_comment_likes 、 @post_comments 、 @post_likes 是会话变量,您可以在它们前面加上 '@' 字符
使用上面的代码,您可以访问每个表的计数。

于 2012-04-27T07:54:39.737 回答
0

请尝试下面给出的mysql查询

SELECT
(SELECT COUNT(*) AS `post` FROM post WHERE user_id = "123456" ) AS post , 
(SELECT COUNT(*) AS `post_comment_likes` FROM post_comment_likes WHERE user_id ="123456") AS post_comment_likes,
(SELECT COUNT(*) AS `post_comments` FROM post_comments WHERE user_id = "123456") AS post_comments , 
(SELECT COUNT(*) AS `post_likes` FROM post_likes WHERE user_id = "123456" ) AS post_likes

谢谢

于 2012-04-27T13:12:13.890 回答
0
SELECT (SELECT COUNT(*) 
          FROM post 
         WHERE user_id = "123456") AS `post`
      ,(SELECT COUNT(*) 
          FROM post_comment_likes
         WHERE user_id = "123456") AS `post_comment_likes`
      ,(SELECT COUNT(*)
          FROM post_comments
         WHERE user_id = "123456") AS `post_comments`
      ,(SELECT COUNT(*)
          FROM post_likes
         WHERE user_id = "123456") AS `post_likes`

您应该替换COUNT(*)COUNT(<some fieldname>)并且可以使用变量作为用户 ID。

于 2012-04-27T07:59:51.623 回答