如何从mysql中的一个表中获取所有数据?

时间:2013-03-21 06:53:40

标签: mysql sql database left-join

我在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 =“某个特定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的视频类型adv ...

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

medianame | count 

animation | 92

video     | 0

Images    | 103

这意味着如果没有来自特定mediatype的advid,那么也会在输出中显示0 Count ..

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

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

1 个答案:

答案 0 :(得分: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 Fiddle Demo

这会给你:

| MEDIANAME | TOTAL |
---------------------
| animation |    13 |
|     image |     2 |
|     video |     0 |