如何将来自不同表的3个select语句合并为1个特定查询?

时间:2015-07-17 19:17:19

标签: mysql

我可以为该表及其关系编写特定查询,但将它们合并为一个就是我遇到的困难

select clients, count(*)
from clients
inner join themes
on clients.id = themes.client_id
group by clients

select themes.id
from themes
inner join videos
on videos.theme_id = themes.id


select distinct videos.user_id, 
from videos
inner join properties
on properties.user_id = videos.user_id
group by properties.user_id
基本上,我想计算一个客户的唯一用户数量

关系是

客户有很多主题

主题有很多视频

视频有一个属性

用户有很多属性

感谢

1 个答案:

答案 0 :(得分:1)

计算客户的唯一身份用户数量:

select clients, count(DISTINCT properties.user_id) as num_users
from clients
inner join themes on clients.id = themes.client_id
inner join videos on videos.theme_id = themes.id
inner join properties on properties.user_id = videos.user_id
group by clients.clients_id;

您也可以使用更短的查询: 用户总是拥有属性(这是假设),然后带有视频的用户将出现在属性表中,然后不必加入:

select clients, count(DISTINCT videos.user_id) as num_users
from clients
inner join themes on clients.id = themes.client_id
inner join videos on videos.theme_id = themes.id
group by clients.clients_id;
相关问题