2013-03-12 76 views
1

我有一个MySQL数据库,并希望插入一些数据。在我的数据库中有两个名称分别为tx_yes_cantonstx_yes_areas的表格。“#1242 - 子查询返回多于1行”,而插入

在州的表中,我想从一个区域获得ID(在我的情况下是uid)。现在当我试试这个:

INSERT INTO `tx_yes_cantons` (tx_yes_areas_uid, cantonname, code) 
    VALUES (
     ((SELECT `uid` FROM `tx_yes_areas` WHERE `areaname` Like 'Genferseeregion'), 'Genf', 'ge'), 
     ((SELECT `uid` FROM `tx_yes_areas` WHERE `areaname` Like 'Mittelland'), 'Freiburg', 'fr'), 
     ((SELECT `uid` FROM `tx_yes_areas` WHERE `areaname` Like 'Nordwestschweiz'), 'Basel-Stadt', 'bs'), 
     ((SELECT `uid` FROM `tx_yes_areas` WHERE `areaname` Like 'Zentralschweiz'), 'Obwalden', 'ow'), 
     ((SELECT `uid` FROM `tx_yes_areas` WHERE `areaname` Like 'Tessin'), 'Tessin', 'ti'), 
     ((SELECT `uid` FROM `tx_yes_areas` WHERE `areaname` Like 'Zürich'), 'Zürich', 'zh'), 
     ((SELECT `uid` FROM `tx_yes_areas` WHERE `areaname` Like 'Ostschweiz'), 'Schaffhausen', 'sh'); 

我在标题中得到错误。为什么?我看不出有什么错..:S

+0

尝试执行所有选择查询。某些查询可能会返回多个行。 – Dhinakar 2013-03-12 11:00:18

回答

1

某些查询返回多个行。如果你需要插入您的tx_yes_cantons表中的所有行,你可能需要这样的事:

INSERT INTO `tx_yes_cantons` (tx_yes_areas_uid, cantonname, code) 
SELECT `uid`, 'Genf', 'ge' 
FROM `tx_yes_areas` WHERE `areaname` = 'Genferseeregion' 
UNION ALL 
SELECT `uid`, 'Freiburg', 'fr' 
FROM `tx_yes_areas` WHERE `areaname` = 'Mittelland' 
UNION ALL 
SELECT `uid`, 'Basel-Stadt', 'bs' 
FROM `tx_yes_areas` WHERE `areaname` = 'Nordwestschweiz' 
UNION ALL 
SELECT `uid`, 'Obwalden', 'ow' 
FROM `tx_yes_areas` WHERE `areaname` = 'Zentralschweiz' 
UNION ALL 
SELECT `uid`, 'Tessin', 'ti' 
FROM `tx_yes_areas` WHERE `areaname` = 'Tessin' 
UNION ALL 
SELECT `uid`, 'Zürich', 'zh' 
FROM `tx_yes_areas` WHERE `areaname` = 'Zürich' 
UNION ALL 
SELECT `uid`, 'Schaffhausen', 'sh' 
FROM `tx_yes_areas` WHERE `areaname` = 'Ostschweiz' 

,或者也:

INSERT INTO `tx_yes_cantons` (tx_yes_areas_uid, cantonname, code) 
SELECT tx_yes_areas.uid, codes.cantonname, codes.code 
FROM 
    tx_yes_areas INNER JOIN (
    SELECT 'Genferseeregion' areaname, 'Genf' cantonname, 'ge' code 
    UNION ALL SELECT 'Mittelland', 'Freiburg', 'fr' 
    UNION ALL SELECT 'Nordwestschweiz', 'Basel-Stadt', 'bs' 
    UNION ALL SELECT 'Zentralschweiz', 'Obwalden', 'ow' 
    UNION ALL SELECT 'Tessin', 'Tessin', 'ti' 
    UNION ALL SELECT 'Zürich', 'Zürich', 'zh' 
    UNION ALL SELECT 'Ostschweiz', 'Schaffhausen', 'sh') codes 
    ON tx_yes_areas.areaname = codes.areaname 
+0

感谢它的工作。但是我已经删除了现在多余的条目。无论如何,我有一个问题。 Select做什么而不是VALUES? – 2013-03-12 12:14:03

+0

@AgashThamo。如果你不想使用reduntant行,你可以使用'UNION'而不是'UNION ALL'或者使用'SELECT DISTINCT tx_yes_areas ...'来修改第一个查询,使用VALUES你只能在一个行中插入一行时间 – fthiella 2013-03-12 13:29:09

1

尝试在数据库中运行以下查询:

select areaname, count(*) from tx_yes_areas group by (areaname) having count(*)>1; 

所有返回将显示可能的重复,在情况下的结果,任何AREANAME的相似一个在插入查询中,然后尝试删除tx_yes_areas表中的多余条目。

+0

非常感谢。我认为我没有红队队员。但我有。我的错误。我删除了entrys,它工作! :D – 2013-03-12 12:12:54

相关问题