当没有找到值时,MySql如何显示零

Sna*_*eet 1 mysql

我有这个问题:

SELECT ent_video_tipo, count(ent_video_tipo) as cnt 
FROM entradas 
WHERE entradas.ent_user= '1' 
GROUP BY ent_video_tipo 
ORDER BY cnt DESC
Run Code Online (Sandbox Code Playgroud)

这会给我:

ent_video_tipo|cnt
       3      | 3
       1      | 3
       4      | 1
       2      | 1
Run Code Online (Sandbox Code Playgroud)

当我做

SELECT ent_video_tipo, count(ent_video_tipo) as cnt 
FROM entradas 
WHERE entradas.ent_user= '2' 
GROUP BY ent_video_tipo 
ORDER BY cnt DESC
Run Code Online (Sandbox Code Playgroud)

我明白了

ent_video_tipo|cnt
       1      | 4
       2      | 2
       3      | 2
Run Code Online (Sandbox Code Playgroud)

而且我希望得到一个零ent_video_tipo = 4.像这样

ent_video_tipo|cnt
       1      | 4
       2      | 2
       3      | 2
       4      | 0
Run Code Online (Sandbox Code Playgroud)

ent_video_tipo 有自己的表:

type_id|type_name
   1   |    a
   2   |    b
   3   |    c
   4   |    d
Run Code Online (Sandbox Code Playgroud)

Abh*_*rty 5

好的,因为ent_video_tipo有自己的类型,你可以使用左连接的东西

SELECT 
evt.type_id, 
coalesce(count(e.ent_video_tipo),0) as cnt 
FROM ent_video_tipo evt
left join entradas e on e.ent_video_tipo = evt.type_id
AND e.ent_user= '2' 
GROUP BY evt.type_id 
ORDER BY cnt DESC ;
Run Code Online (Sandbox Code Playgroud)

DEMO

更新 这是另一种方法

select
evt.type_id,
coalesce(cnt,0) as cnt
from ent_video_tipo evt
left join
(
  select
  ent_video_tipo,
  count(ent_video_tipo) as cnt
  FROM entradas 
  WHERE ent_user= '2' 
  GROUP BY ent_video_tipo 
)e
on e.ent_video_tipo = evt.type_id
Run Code Online (Sandbox Code Playgroud)

DEMO