如何从单个查询中的多个表中获取数据

时间:2013-11-13 05:56:41

标签: mysql sql

我有以下表格

具有列名称的User表(UserId,Name,email)

包含列名称的视频表(UserId,VideoLink)

如果status = 0,则列名为(UserId,Status)的Activity表,如果status = 1则不喜欢

我想得到以下结果

名称 Total_Videos_posted_by_that_user 计数(喜欢)计数(不喜欢)

如何在一个查询中查询它们?

1 个答案:

答案 0 :(得分:3)

select u.name, 
       videocount, 
       dislikes,
       likes
from user u
left join 
(
  select u.name, count(v.videolink) as videocount
  from user u
  inner join videos v on v.userid = u.userid
) x on x.name = u.name
left join 
(
  select u.name, 
         sum(a.status=1) as dislikes,
         sum(a.status=0) as likes
  from user u
  inner join activity a on a.userid = u.userid
) y on y.name = u.name

SQLFiddle demo