2

我有一个 MySQL 数据库,想插入一些数据。在我的数据库中,有两个名为tx_yes_cantons和的表tx_yes_areas

在 cantons 表中,我想获得一个地区的 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

4

2 回答 2

2

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

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

返回的所有结果都将显示可能的重复项,以防任何 areaname 与插入查询中的一个相似,然后尝试从 tx_yes_areas 表中删除冗余条目。

于 2013-03-12T11:04:09.667 回答
2

某些查询返回不止一行。如果您需要在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
于 2013-03-12T11:04:19.420 回答