如何在一个查询中使用内连接获取列值的总和?

时间:2013-02-12 06:12:26

标签: mysql sql database inner-join

我有一个表名为a_ad_display,我有下表

advId | Displaytime

我有一个带有以下collumn的a_advertise表

advertiseId| advertisename| mediaTypeId

我有一个带有以下collumn的a_mediatype表

mediaTypeId | medianame

1 | Image
2 | Animation
3 | video

在a_display表中有多个advId条目

我想用他们的mediaType获取adv显示的总和,比如a_display表中广告的视频,图像和动画类型

我这样做了

SELECT 
  mdtype.medianame AS _type,
  SUM(mdtype.medianame = 'Image') AS _display 
FROM
  a_ad_display a 
  INNER JOIN a_advertise adv 
    ON adv.advertiseId = a.advId 
  INNER JOIN a_mediatype mdtype 
    ON mdtype.mediaId = adv.mediaTypeId 
GROUP BY medianame ;

但我得到了以下结果

enter image description here

但如果只写和(不同的mdtype.medianame)那么它会给我带来错误...那么如何才能在一个查询中获得图像视频和动画的所有值?

4 个答案:

答案 0 :(得分:3)

SELECT
    m.medianame,
    COUNT(as.advId) as Total
FROM    a_mediatype as m
INNER JOIN a_advertise as a ON a.mediaTypeId = m.mediaTypeId
INNER JOIN  a_ad_display as ad ON ad.advId = a.advertiseId
GROUP BY m.mediaTypeId

答案 1 :(得分:1)

试试这个......

SELECT mdtype.medianame as _type, SUM(mdtype.medianame) as _display
FROM a_ad_display a
INNER JOIN a_advertise adv ON ad.advertiseID=a.advId
INNER JOIN a_mediatype mdtype ON mdtype.mediaID=adv.mediaTypeId
GROUP BY _type
HAVING DISTINCT(_type)

答案 2 :(得分:1)

你可以试试这个

SELECT m.mediaTypeId, 
       MIN(m.medianame) AS `type`, 
       COUNT(m.mediaTypeId) AS `count`
  FROM a_ad_display a LEFT JOIN 
       a_advertise d on d.advertiseId=a.advId LEFT JOIN 
       a_mediatype m on m.mediaId=d.mediaTypeId 
GROUP BY m.mediaTypeId

答案 3 :(得分:1)

试试这个:

SELECT
    m.medianame,
    COUNT(as.advId) as Total
FROM a_mediatype as m
INNER JOIN a_advertise as a 
ON a.mediaTypeId = m.mediaTypeId
INNER JOIN  a_ad_display as ad 
ON ad.advId = a.advertiseId
GROUP BY m.mediaTypeId