mysql,@ variable和if语句

问题描述 投票:0回答:2

伙计们,我遵循这个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个最大的城市

我错过了什么吗?谢谢

mysql variables if-statement
2个回答
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;

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;
© www.soinside.com 2019 - 2024. All rights reserved.