2015-04-03 138 views
0

家伙, 我按照指示,从这个link的MySQL,@variable和if语句

我创建的表像这样

CREATE TABLE cities 
(
    city VARCHAR(80), 
    country VARCHAR(80), 
    population INT 
); 

INSERT INTO cities VALUES ('New York', 'United States', 8175133); 
INSERT INTO cities VALUES ('Los Angeles', 'United States', 3792621); 
INSERT INTO cities VALUES ('Chicago', 'United States', 2695598); 

INSERT INTO cities VALUES ('Paris', 'France', 2181000); 
INSERT INTO cities VALUES ('Marseille', 'France', 808000); 
INSERT INTO cities VALUES ('Lyon', 'France', 422000); 

INSERT INTO cities VALUES ('London', 'United Kingdom', 7825300); 
INSERT INTO cities VALUES ('Birmingham', 'United Kingdom', 1016800); 
INSERT INTO cities VALUES ('Leeds', 'United Kingdom', 770800);  
当我运行此查询

SELECT city, country, population 
    FROM 
    (SELECT city, country, population, 
       @country_rank := IF(@current_country = country, @country_rank + 1, 1) AS country_rank, 
       @current_country := country 
    FROM cities 
    ORDER BY country, population DESC 
    ) ranked 
    WHERE country_rank <= 2; 

它doesn”

t给我每个国家2个最大的城市

是否有我错过了什么?感谢

+0

工作对我来说:http://www.sqlfiddle.com/#!9/6a5a1/1 – Barmar 2015-04-03 03:36:22

+0

它不工作对我来说,我检查了我的MySQL版本,它说5.0 也许我应该升级到5.6 谢谢@Barmar – 2015-04-03 03:51:52

回答

0

添加下面的两个线路码的代码之前,它会工作。

select @current_country:=NULL; 
select @country_rank:=0; 


SELECT city, country, population 
    FROM 
    (SELECT city, country, population, 
      @country_rank := IF(@current_country = country, @country_rank + 1, 1) AS country_rank, 
      @current_country := country 
    FROM cities 
    ORDER BY country, population DESC 
    ) ranked 
    WHERE country_rank <= 2; 
+0

它的工作原理;非常感谢 – 2015-04-03 09:43:37

0

尝试增加其他子查询初始化变量:

SELECT city, country, population 
FROM 
    (SELECT city, country, population, 
      @country_rank := IF(@current_country = country, @country_rank + 1, 1) AS country_rank, 
      @current_country := country 
    FROM cities 
    ORDER BY country, population DESC 
) ranked 
CROSS JOIN (SELECT @country_rank := 0, $current_country := '') vars 
WHERE country_rank <= 2;