MySQL联盟的情况

时间:2012-11-21 10:31:47

标签: mysql database

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

先谢谢

我认为A部分答案:

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

B部分:将A部分的查询写为UNION?

2 个答案:

答案 0 :(得分:0)

试试这个

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

使用“union”时你不会得到单独列的结果。你会得到同一列的结果

答案 1 :(得分: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 |
+-----------+------------------+