我在制作MySQL查询时遇到了另一个问题。
我有两个数据库,每个数据库都有一个包含城市的数据库。 我的客户从另一家公司获得了他的旧网站,我需要获得旧数据库城市和新数据库之间的关联。
这是数据库的结构:
数据库1
CREATE TABLE new_cities (
new_id INT PRIMARY KEY,
new_postal_code INT,
new_city_name VARCHAR(255)
);
的Database2
CREATE TABLE old_cities (
old_id INT PRIMARY KEY,
old_postal_code INT,
old_city_name VARCHAR(255)
);
CREATE TABLE old_entries (
entry_id INT PRIMARY KEY,
city_id INT
);
所以我必须将数据库中的条目传输到另一个数据库,但问题是old_entries.old_city_id将不会与新数据库中的正确城市相对应,因为ID是不同的。
我想得到我的old_entries。*加上一个字段(或直接替换old_city_id),其中包含我将通过zipcode对应获得的new_city_id。
这是我当前的查询不起作用:
SELECT *,
(SELECT database1.new_cities.id FROM database1.new_cities, database2.old_entries WHERE database1.new_cities.zipcode =
(SELECT database2.old_cities.cp FROM database2.old_cities, database2.old_entries WHERE database2.old_entries.city_id = database2.old_cities.old_id)
) AS newcp FROM database2.old_entries WHERE 1
我得到的逻辑消息是我的子查询返回多行。
结构应该是:
1 - 带上我的old_entry
2 - 获取old_entry.city_id并从old_cities表中获取相应的邮政编码
3 - 获取此邮政编码并获取与此邮政编码相对应的new_cities.new_id
4 - 将此new_id添加到AS newcp行(或直接用它替换city_id的值)
如何让查询为每一行获取相应的new_city_id AS newcp?
编辑:样本
参赛样本:
ID| CITY_ID
1 | 23000
old_cities样本
ID | ZIPCODE | NAME
23000 | 75000 | Paris
new_cities示例
ID | ZIPCODE | NAME
23000 | 13000 | Marseille
23500 | 75000 | Paris
预期结果:
ID | OLD_CITY_ID | NEW_CITY_ID
1 | 23000 | 23500
或最终
ID | CITY_ID
1 | 23500
所以我们可以看到,如果我的转移条目保留其city_id,它将不再对应巴黎而是马赛,所以我需要将entry.city_id中的23000替换为23500,这是新的id。巴黎市,由其邮政编码(75000)
标识答案 0 :(得分:1)
获取相应新城市ID的查询如下:
SELECT database2.old_entries.entry_id AS id, database1.new_cities.new_id AS city_id
FROM database2.old_entries AS entries
JOIN database2.old_cities AS old_cities ON (entries.city_id = old_cities.old_id)
JOIN database1.new_cities AS new_cities ON (old_cities.old_postal_code = new_cities.new_postal_code)
这将返回具有匹配的新城市ID的所有条目ID。另请参阅JOIN的工作原理。
如果要将结果插入表格,则可以使用以下查询:
INSERT INTO new_entries (entry_id, city_id)
SELECT database2.old_entries.entry_id AS id, database1.new_cities.new_id AS city_id
FROM database2.old_entries AS entries
JOIN database2.old_cities AS old_cities ON (entries.city_id = old_cities.old_id)
JOIN database1.new_cities AS new_cities ON (old_cities.old_postal_code = new_cities.new_postal_code)