2012-11-21 105 views
0

我正在尝试学习数据库(特别是MySQL),我正在考虑购买的教科书中的问题(没有提供解决方案手册)。我已经实现了问题的A部分,但我很困惑我将如何做B部分。除了使用UNION之外,B部分需要获得与部分A相同的结果。我想知道有人能解释吗?MySQL联盟情况

由于提前

部分在我看来,答案是:

SELECT Country, COUNT(City) from country LEFT OUTER JOIN city 
ON city.CountryId = country.CountryId group by Country; 

B部分:写A部分查询作为UNION?

回答

0
select c1.countrynm,count(c2.citynm) 
from country c1 
join city c2 
on c2.countryid=c1.countryid 
group by c1.countrynm 
union select countrynm,0 from country where 7=3; 

mysql> select c1.countrynm,count(c2.citynm) 
-> from country c1 
-> join city c2 
-> on c2.countryid=c1.countryid 
-> group by c1.countrynm 
-> union select countrynm,0 from country where 7=3; 
+-----------+------------------+ 
| countrynm | count(c2.citynm) | 
+-----------+------------------+ 
| France |    2 | 
| Germany |    1 | 
+-----------+------------------+ 
+0

感谢您的回答。你介意说明C1,countrynm,c2和citynm与我在A部分的查询有什么关系?将接受。谢谢 –

+0

特别是什么是“where 7 = 3”? –

+0

是一种笑话亚历克斯。我无法弄清楚。其中7 = 3意味着返回没有任何因为他们不相等。高低搜索。很想知道这个答案。 c1和c2是别名。 – Drew

0

试试这个

select country from country group by country 
union 
select count(city) from city group by city 

,而使用“联盟”,你将不会导致单独column.You将获得导致同一列

+0

感谢您的快速回复。对此,我不确定是否正确,因为它放在一张表中。根据我见过的其他例子,我认为他们的意思是把它放在一张桌子上,但有不同的栏目(就像你提到的那样)。你知道如何做到这一点?谢谢! –