2015-08-21 91 views
0

我使用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 

我想從表香檳數據transfert表結構。 問題是插入了一行。爲什麼?

我的要求:

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 
+0

什麼是數據的所有行? brut table上的每一行在類型學和國家表上都有匹配的行嗎? – Kickstart

+0

答案。恩,那就對了。 –

+0

如果只執行SELECT部分​​會發生什麼? – jarlh

回答

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) 
+0

還有一個名爲'Select INTO'的結構,你可以使用,在這裏你有一個URL:http://www.w3schools.com/sql/sql_select_into.asp – inetphantom

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) 
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 

而且我插入:-)

+0

太棒了! !很高興聽到。 –