加入子查询

时间:2015-10-02 11:29:54

标签: mysql select join count

我需要在count子查询中使用联接。

这是我的代码,所以你可以看到我正在尝试做的事情:

select verticals.name,
        (select count(*) from `leads` where `id_vertical` = verticals.id) as `unique_leads`,
        (select count(*) from `lead_history` where `id_vertical` = verticals.id) as `all_leads`,
        (select count(a.*) 
            from `assignments` as a
            left join `leads` as l on (l.id = a.id_lead)
            where l.id_vertical = verticals.id) as `assigned`
        from verticals

我收到语法错误,因为我猜测我的查询完全不正确。写这个的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

我认为这应该可以解决错误:

select v.name,
       (select count(*) from `leads` where `id_vertical` = v.id) as `unique_leads`,
       (select count(*) from `lead_history` where `id_vertical` = v.id) as `all_leads`,
       (select count(*) 
        from `assignments` a left join
             `leads` l 
             on (l.id = a.id_lead)
        where l.id_vertical = v.id
       ) as `assigned`
from verticals v;

这也使用表别名(对于verticals) - 因此查询更容易编写和阅读。

答案 1 :(得分:0)

使用join来提高查询性能。

select t.id,t.name,
count(a.id) as unique_leads,
count(b.id) as all_leads,
count(c.id) as assigned
from verticals t
inner join leads a on a.id_vertical = t.id
inner join lead_history b on b.id_vertical = t.id
inner join assignments c on a.id = c.id_lead
group by t.id,t.name