0

我在mysql数据库中有以下表格

a_ad_display

id | advId | 

a_mediatype

id | mediaId
 1 | animation 
 2 | Video
 3 | Image

a_advertise

advId | mediatypeId | organizationId

现在我想要的是从 a_ad_display 中获取 advId 的所有记录,其中 advId 的计数在广告表中注册到 organizationId="some specific id" 并使用它们的媒体类型进行分组。

我通过以下查询实现了这一点....

SELECT COUNT(a.advertiseId) as Total ,m.medianame

FROM a_mediatype as m

 JOIN a_advertise as a ON a.mediaTypeId = m.mediaId

 JOIN  a_ad_display as ad ON ad.advId = a.advertiseId

where a.organizationId in(SELECT t.organizationId

FROM organization_ AS t JOIN organization_ AS p ON  t.treePath LIKE CONCAT( p.treePath, '%')

where p.organizationId ='37423')  GROUP BY m.medianame

但我的输出是这样的

  medianame | count 
  animation | 92
  Images    | 103

所以这意味着 a_ad_display 中没有具有特定组织 ID 的视频类型 advId ...

但我想要的是如下......

medianame | count 

animation | 92

video     | 0

Images    | 103

这意味着如果没有来自特定媒体类型的建议,那么也会在输出中显示 0 Count..

任何人都可以在这个问题上给我一些指导吗?

看我的 sql fiddle 演示 http://sqlfiddle.com/#!2/391a2/11

4

1 回答 1

1

改用LEFT JOIN

SELECT 
  m.medianame,
  IFNULL(COUNT(ad.id), 0) AS Total 
FROM a_mediatype as m
LEFT JOIN a_advertise   AS a   ON a.mediaTypeId    = m.mediaId
LEFT JOIN a_ad_display  AS ad  ON ad.advId         = a.advId
LEFT JOIN organization_ AS o   ON a.organizationId = o.organizationId
LEFT JOIN organization_ AS p   ON o.organizationId = p.organizationId 
                              AND p.organizationId = '37423'  
                              AND o.treePath       LIKE CONCAT( p.treePath, '%')
GROUP BY m.medianame;

SQL 小提琴演示

这会给你:

| MEDIANAME | TOTAL |
---------------------
| animation |    13 |
|     image |     2 |
|     video |     0 |
于 2013-03-21T06:56:01.373 回答