【问题标题】:MySQL, Select inside Select Distinct returns more than one valueMySQL, Select inside Select Distinct 返回多个值
【发布时间】:2016-08-11 13:39:44
【问题描述】:

我正在尝试使用主表中的值创建一些表。精通 PHP,但不精通 MySQL。 主表有这些列:

Table Places
ISO
Country
Language
Region2 (is the estate)
Region4 (is ths city council)
ID (id for locality)
Locality

获取国家并不困难:

CREATE TABLE countries ( id integer(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
iso varchar(2) NOT NULL, language varchar(2) NOT NULL, 
name varchar(50) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO countries ( iso , language, name) 
SELECT DISTINCT ISO AS iso, Language as language, Country AS name FROM Places WHERE 1;

现在我必须创建州、议会和城市,并且我已经尝试了两天来使用类似这样的州(我尝试了一些不同的代码):

CREATE TABLE states ( id integer(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
country_id integer(11) UNSIGNED NOT NULL, country_iso varchar(2) NOT NULL, 
name varchar(80) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO states (country_id, country_iso, name) 
SELECT DISTINCT 
  (SELECT countries.id AS country_id from countries WHERE countries.iso = Places.ISO),
  ISO as country_iso ,
  Region2 AS name FROM Places WHERE 1;

但对于 country_id,此 Select 会返回所有国家/地区 ID。 我只需要在 Countrys.iso 与 Places 中的 ISO 匹配的国家/地区表中获取国家/地区 ID。

在这张表之后,States,我必须创建委员会,从 Places 中获取值,再次使用 Select Distinct,并再次尝试从 States 中获取 state id,也可能是 de country id。

拜托,任何人都可以让我正确地嵌套这个选择吗? 谢谢。

【问题讨论】:

    标签: mysql select nested


    【解决方案1】:

    看来你需要加入

    INSERT INTO states (country_id, country_iso, name) 
    SELECT DISTINCT  countries.countries.id , ISO, Places.Region2
    from countries 
    inner join Placesc on countries.iso = Places.ISO
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 2014-07-10
      • 1970-01-01
      • 2011-11-16
      • 2015-01-28
      相关资源
      最近更新 更多