SQL - 连接多个表和count()

时间:2016-12-15 22:57:26

标签: mysql sql join

我正在尝试在加入表后计算列中的结果数,并且我很难让我的查询工作。

在最终结果中,我需要获得一张表格,其中包含产品ID,产品名称和每种产品的媒体数量

这是我到目前为止所做的:

SQL

select 
    p.id, 
    p.name, 
    count(distinct mp.media_id)
from products as p
left join medias_products as mp
    on mp.product_id = p.id
group by mp.media_id
order by p.id

这些是表格:

媒体

Id     | client id
------ | ---------
1      | 1
2      | 2

产品

id     | name     | client_id
------ | -------- | ---------
1      | product1 | 1
2      | product2 | 2

medias_products

product_id | media_id
---------- | --------
1          | 2
2          | 1

客户端

id     | name
------ | -----
1      | Peter
2      | John

此外,我想找到另一个查询,它会给我按特定客户端ID过滤的结果。

有人可以透露一些亮点并分享知识。

提前致谢。

2 个答案:

答案 0 :(得分:0)

试试这个:

select 
    p.id, 
    min(p.name) as name, 
    count(distinct mp.media_id) as medias
from products as p
left join medias_products as mp
    on mp.product_id = p.id
group by p.id
order by p.id

第二个问题:

select 
    p.id, 
    min(p.name) as name, 
    count(distinct mp.media_id) as medias
from products as p
inner join medias_products as mp
    on mp.product_id = p.id
inner join medias as m
    on m.id = mp.media_id
inner join clients as c
    on c.id = m.client_id
where c.id = <your client's id>
group by p.id
order by p.id

答案 1 :(得分:0)

不应该是GROUP BY p.id而不是mp.media_id吗?那是

select 
    p.id, 
    p.name, 
    count(distinct mp.media_id)
from 
    products as p
    left join medias_products as mp
        on p.id = mp.product_id
group by p.id
order by p.id