我有一个MySQL数据库,想要插入一些数据。在我的数据库中有两个名为tx_yes_cantons
和tx_yes_areas
的表。
在州表中,我希望从一个区域获得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 :(得分: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
答案 1 :(得分:1)
尝试在数据库中运行以下查询:
select areaname, count(*) from tx_yes_areas group by (areaname) having count(*)>1;
返回的所有结果将显示可能的重复项,以防任何isaname与插入查询中的任何一个相似,然后尝试从tx_yes_areas表中删除冗余条目。