0

I have a table with news items, I have another table with media_types, I want to make one simple query that reads the media_types table and count for each record how many news_items exist.

The result will be turned into a json response that I will use for a chart, this is my SQLstatement

SELECT
  gc.country AS "country"
, COUNT(*) AS "online"
FROM default_news_items AS ni
JOIN default_news_item_country AS nic ON (nic.id = ni.country)
JOIN default_country AS c ON (nic.country = c.id)
JOIN default_geo_country AS gc ON (gc.id = c.geo_country)
LEFT JOIN default_medias ON (m.id = ni.media)
WHERE TRUE
  AND ni.deleted = 0
  AND ni.date_item > '2013-10-23'
  AND ni.date_item < '2013-10-29'
AND gc.country <> 'unknown'
AND m.media_type = '14'
GROUP BY gc.country
ORDER BY `online` desc LIMIT 10

This is the json respond I create from the mysql respond

   [
     {"country":"New Zealand","online":"7"},
     {"country":"Switzerland","online":"1"}
   ]

How do I add print and social data to my output like this

I would like the json respond look like this

   [
     {"country":"New Zealand","online":"7", "social":"17", "print":"2"},
     {"country":"Switzerland","online":"1", "social":"7", "print":"1"}
   ]

Can I use the count (*) in the select statement to do something like this

COUNT( * ) as online, COUNT( * ) as social, COUNT( * ) as print

Is it possible or do I have to do several SQL statement to get the data I'm looking for?

4

2 回答 2

0

这是一般结构:

SELECT default_geo_country.country as country,
       SUM(default_medias.media_type = 14) as online,
       SUM(default_medias.media_type = XX) as social,
       SUM(default_medias.media_type = YY) as print
FROM ...
JOIN ...
WHERE ...
GROUP BY country
于 2013-10-29T15:16:16.563 回答
0

我认为你想要条件聚合。但是,您的问题仅显示在线媒体类型。

通过使用表别名并删除反引号,您的查询将更具可读性。此外,如果media_type是一个整数,那么您不应该将用于比较的常量括在单引号中——首先,我发现将字符串常量与整数列进行比较会产生误导。

我怀疑这是你想走的路。在哪里. . .,您要填写其他媒体类型的计数。

SELECT default_geo_country.country as country,
       sum(media_type = '14') as online,           
       sum(default_medias.media_type = XX) as social,
       sum(default_medias.media_type = YY) as print
       . . . 
FROM default_news_items ni JOIN
     default_news_item_country nic
     ON nic.id = ni.country JOIN
     default_country dc 
     ON nic.country = dc.id JOIN
     default_geo_country gc
     ON gc.id = dc.geo_country LEFT JOIN
     default_medias dm
     ON dm.id = dni.media
WHERE ni.deleted = '0' 
 AND ni.date_item > '2013-10-23' 
 AND ni.date_item < '2013-10-29' 
 AND gc.country <> 'unknown' 
GROUP BY gc.country
ORDER BY online desc
LIMIT 10
于 2013-10-29T15:20:43.907 回答