MYSQL:用union三表选择count

时间:2016-10-17 16:44:55

标签: php mysql sql union

我有三个关于帖子的表内容信息

并且每个表都有Post_id它是Post表的foreign_key

first table = `likes`  
second table = `Comment`  
and last one = `Visitor` 

每个表都有一些关于会话或身份等用户的信息

我需要创建新的视图表,其中包含帖子ID和访客数量,赞,评论

我试过这个

SELECT *


  from (

 select id   , count(id) as Comment  
from Post left join Comment  on  id = Post_id 
group by id

  UNION

select id, count(id) as Visitor    
from Post left join Visitor  on id = Post_id 
group by id
UNION

select id, count(id) as Likes  
from Post left join Likes  on id = Post_id 
group by id

) CountsTable
GROUP BY CountsTable.id

但它没有用。 我不知道为什么结果只是第一个内部选择

在我的例子中,结果是

|    id  | Comment| 
|--------|------- | 
|    1   |   55   |    
|    2   |   25   |   
|    3   |   12   |   

我希望有类似的东西

| id | Comment | Likes | Visitor |
|--------------|-------|---------|
|  1 |   55    |  100  |   2000  |    

3 个答案:

答案 0 :(得分:0)

无需使用UNION。计算所有三个表中每个帖子的记录,并使用Post

计算左连接结果

尝试这样的事情

SELECT id,
        comments,
        vistors,
        likes
FROM   Post p
        LEFT JOIN (SELECT Count(Post_id) comments, Post_id
                    FROM   Comment
                    GROUP  BY Post_id) c
                ON p.id = c.Post_id
        LEFT JOIN (SELECT Count(Post_id) vistors, Post_id
                    FROM   Visitor
                    GROUP  BY Post_id) v
                ON p.id = v.Post_id
        LEFT JOIN (SELECT Count(Post_id) likes, Post_id
                    FROM   Likes
                    GROUP  BY Post_id) l
                ON p.id = l.Post_id 

答案 1 :(得分:0)

您可以使用Left Join查询来执行此操作,例如:

select u.id, count(distinct l.id) as likes, count(distinct c.id) as comments
from user u left join likes l on u.id = l.user_id
left join comments c on u.id = c.user_id
group by u.id;

这是 SQL Fiddle

答案 2 :(得分:0)

SELECT id, SUM(Comment),SUM(Visitor),SUM(Likes) from (

select id   , count(id) as Comment, 0 as Visitor, 0 as Likes  
from Post left join Comment  on  id = Post_id 
group by id

UNION ALL

select id, 0 as Comment, count(id) as Visitor , 0 as Likes    
from Post left join Visitor  on id = Post_id 
group by id

UNION ALL

select id, 0 as Comment, 0 as Visitor, count(id) as Likes  
from Post left join Likes  on id = Post_id 
group by id

) CountsTable
GROUP BY CountsTable.id
相关问题