dongque8332 2016-10-17 16:44
浏览 226

MYSQL:用union三表选择count

I have three table content information about posts

and each table has Post_id it's foreign_key for Post table

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

each Table has some info about users like session or id and etc

i need to create new view table contain post id and the number of visitor , likes , comment

i tried this

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

but it didnt work . i dont know why the result is only the first inner select

in my example the result is

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

i expect something like that

| id | Comment | Likes | Visitor |
|--------------|-------|---------|
|  1 |   55    |  100  |   2000  |    
  • 写回答

3条回答 默认 最新

  • doucha4054 2016-10-17 16:48
    关注

    No need to use UNION. Count the records for each post in all three tables and Left Join result with Post table

    Try something like this

    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 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探