mysql,@ variable和if语句

时间:2015-04-03 03:30:13

标签: mysql variables if-statement

人, 我按照link

的说明进行操作

我创建了这样的表

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;

它并没有为每个国家提供2个最大的城市

我错过了什么吗?感谢

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

在您的代码之前添加以下两行代码,它将起作用。

SET @current_country:=NULL;
SET @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;