我想使用MySQl在一个结果中组合多个表结果计数

时间:2012-04-27 07:43:52

标签: mysql database optimization logic

我想在一个结果中使用 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" 

3 个答案:

答案 0 :(得分: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是会话变量,你在它们前面加上'@'字符
使用上面的代码,您可以访问每个表的计数。

答案 1 :(得分: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。

答案 2 :(得分: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

感谢