如何通过查询在mySQL组中显示零计数的行?

时间:2011-07-06 20:12:40

标签: mysql sql

我试着寻找类似的解决方案,但在我的情况下似乎没什么帮助。我有一张桌子:

locations => |longname|name|locations|

topics    => |longname|name|tag|

我正在尝试为特定位置获取具有特定atag的长名计数。我到目前为止的查询也试图强制重新排序,这就是你看到location INFIELD的原因。但是,如果特定标记的位置中没有任何人,则它会完全从响应中省略它。我希望它能返回0.我怎么能这样做?

select count(b.longname) as count, a.location 
 from `topics` b, locations a 
  where tag = 'atag' and a.longname = b.longname 
  and location IN ('Japan', 'France', 'Italy') 
  group by location 
  order by FIELD(location, 'Japan', 'France', 'Italy')

1 个答案:

答案 0 :(得分:4)

也许这个? :

SELECT COUNT(t.longname) as cnt, l.location 
FROM locations l 
  LEFT JOIN topics t
    ON  t.longname = l.longname
    AND t.tag = 'atag'      
WHERE l.location IN ('Japan', 'France', 'Italy') 
GROUP BY l.location 
ORDER BY FIELD(l.location, 'Japan', 'France', 'Italy')