我有一个包含新闻项的表,我有另一个表media_types
,我想创建一个简单的查询,读取media_types
表并计算每个记录的news_items
存在。
结果将变成我将用于图表的json响应,这是我的SQL语句
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
这是我从mysql响应中创建的json响应
[
{"country":"New Zealand","online":"7"},
{"country":"Switzerland","online":"1"}
]
如何将打印和社交数据添加到我的输出中
我希望json回复看起来像这样
[
{"country":"New Zealand","online":"7", "social":"17", "print":"2"},
{"country":"Switzerland","online":"1", "social":"7", "print":"1"}
]
我可以使用select语句中的count (*)
来执行类似这样的操作吗
COUNT( * ) as online, COUNT( * ) as social, COUNT( * ) as print
是否可以或者我必须做几个SQL语句来获取我正在寻找的数据?
答案 0 :(得分: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
答案 1 :(得分: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