为什么只插入一行?

时间:2015-08-21 08:41:47

标签: mysql sql

我使用3个表来插入第4个表的数据。 我的桌子:

Typology
id_typo------PK
name_typology----

Country
id_country---PK
name_country---

Brut
id_brut------PK
name_typology--
name_country---

Structure
id_struct---PK
id_typo-----fk
id_country---fk

我想将表Brut中的数据传输到表Structure。 问题是插入了一行。为什么?

我的要求:

INSERT INTO structure (id_struct,id_typo,id_country) 
SELECT x.id_struct,y.id_typo, z.id_country,
FROM brut AS x, typology AS y, country AS z 
WHERE x.name_typology = y.name_typology AND x.name_country = z.name_country

3 个答案:

答案 0 :(得分:1)

如果表y和表中没有匹配的行,请使用左连接。 z以便至少从表x获得所有行:

    INSERT INTO structure (id_struct,id_typo,id_country) 
    SELECT x.id_struct,y.id_typo, z.id_country,
    FROM brut AS x 
    left join typology AS y on trim(x.name_typology) = trim(y.name_typology)
    left join country AS z on trim(x.name_country) = trim(z.name_country)

答案 1 :(得分:0)

可能是关于名称空间的问题 使用此查询删除空格

INSERT INTO structure (id_struct,id_typo,id_country) 
SELECT x.id_struct,y.id_typo, z.id_country,
FROM brut AS x, typology AS y, country AS z 
WHERE trim(x.name_typology) = trim(y.name_typology) AND trim(x.name_country) = trim(z.name_country)

答案 2 :(得分:0)

非常感谢你。所有问题都得到解决。 我把LEFT JOIN:

INSERT INTO structure (id_struct,id_typo,id_country)  
SELECT x.id_struct,y.id_typo, z.id_country,
FROM brut as x
LEFT JOIN typology as y
ON x.name_typology = y.name_typology
LEFT JOIN country as z 
ON x.name_country = z.name_country

我插入了所有行: - )