Mysql sql从2表中选择并计数
第一表(公司) 第二张表(操作) 结果应该是这样的Mysql sql从2表中选择并计数,mysql,sql,Mysql,Sql,第一表(公司) 第二张表(操作) 结果应该是这样的 LOGO Total new repaired Consists ../763.jpg 4 2 1 1 ../345.jpg 2 2 0 0 ../678.jpg 3 0 2 1 使用联接和条件聚合: select c
LOGO Total new repaired Consists
../763.jpg 4 2 1 1
../345.jpg 2 2 0 0
../678.jpg 3 0 2 1
使用
联接
和条件聚合:
select c.logo, count(*) as total,
sum( status = 'new' ) as new,
sum( status = 'repaired' ) as repaired,
sum( status = 'consists' ) as consists,
from company c left join
operations o
on c.id = o.company_id
group by c.logo;
您也可以使用下面的查询
select
c.logo,
(select count(1) from operation where company_id = o.company_id group by company_id)
as Total,
(select count(1) from operation where company_id = o.company_id and status = 'new'
group by status) as new,
(select count(1) from operation where company_id = o.company_id and status =
'repaired' group by status) as repaired,
(select count(1) from operation where company_id = o.company_id and status =
'consists' group by status) as consists
from
company c
inner join operation o
on (c.id = o.company_id);
@戈登,很好的提问方式。向你学习更多
select c.logo, count(*) as total,
sum( status = 'new' ) as new,
sum( status = 'repaired' ) as repaired,
sum( status = 'consists' ) as consists,
from company c left join
operations o
on c.id = o.company_id
group by c.logo;
select
c.logo,
(select count(1) from operation where company_id = o.company_id group by company_id)
as Total,
(select count(1) from operation where company_id = o.company_id and status = 'new'
group by status) as new,
(select count(1) from operation where company_id = o.company_id and status =
'repaired' group by status) as repaired,
(select count(1) from operation where company_id = o.company_id and status =
'consists' group by status) as consists
from
company c
inner join operation o
on (c.id = o.company_id);