我正在加入大量的表格,我想计算company2city表中公司的数字城市,同时将其链接到公司表格中的一行,然后查明结束时间是否超过现在.. company2city是一个与市表联系在一起的多对多表。一个公司可以有很多城市,它位于company2city表中。
SELECT COUNT(company2city.cityid) as location, city.city
FROM company
INNER JOIN company2city ON company.id = company2city.companyid
INNER JOIN city ON company2city.cityid = city.id AND company.endtime > now()
GROUP BY company2city.cityid
该select语句有效,但它只选择那些在company2city表中有实例且city.endtime超过now()的城市。我想要的是选择city表中的所有城市,如果是company.endtime()> now()失败它只会使COUNT(company2city.cityid)为location = 0
我该如何做这样的选择陈述?
答案 0 :(得分:2)
我相信你想要的是一个Left Join而不是一个Inner Join。左连接无论如何都会连接,并且在无法进行连接的情况下返回null。
试试这个
SELECT COUNT(company2city.cityid) as location, city.city
FROM city
LEFT JOIN company2city on city.id = company2city.cityid
LEFT JOIN company on company.id = company2city.companyid
where company.endtime > now()
group by city.city
答案 1 :(得分:1)
我想的是
SELECT COALESCE (COUNT (company2city.cityid), NULL) AS location, city.city
FROM company
LEFT JOIN company2city
ON company.id = company2city.companyid
LEFT JOIN city
ON company2city.cityid = city.id AND company.endtime > now ()
GROUP BY company2city.cityid
应该适合你。我从未在使用MYSQL的select中尝试过coalece,但我知道它可以与Oracle一起使用。但关键是使用Left连接而不是内连接。