gpt4 book ai didi

mysql - 如何使用从 3 个连接表返回的数据填充表

转载 作者:行者123 更新时间:2023-11-29 13:25:12 24 4
gpt4 key购买 nike

我有4张 table

 1. the first table(d_cities) for cities // related with the next table  by country_id
CityId |CountryID |RegionID |City |Latitude|Longitude

2. the second table(d_country) for countries
CountryId|Country

3. the third table(ip2location_db11) for ip
ip_from|ip_to |country_code|country_name| city_name

4 the fourth table (ip_relation) would be like this
CountryID |CityId|ip_from |ip_to

我创建第四个表来从三个表中收集自定义数据并将其放入一个表中。该遗嘱已由以下人员完成:

通过 id 加入 (d_country,d_cities),然后将此名称与 IP 表进行比较(如果匹配)它将获取这些匹配的名称和 ip 的 id 并将其放入第四个表中..所以我这样写代码并且需要支持修改此代码

INSERT ip_relations (CountryID, CityId,ip_from,ip_to)
SELECT *
FROM d_cities
INNER JOIN d_country ON d_cities.CountryID = d_country.CountryId
INNER JOIN ip2location_db11 ON ip2location_db11.country_name = d_country.Country
AND ip2location_db11.city_name = d_cities.City

///这个sql语句不起作用

最佳答案

首先,我不确定你为什么要这样设计表格。也许你可以像下面这样更改它们:

 d_cities: city_id | country_id | region_id  |city | latitude| longitude 
d_country: country_id | country
ip2location_db11: ip_from | ip_to | country_code | city_id

pS:我不太清楚country_code是什么意思,所以我保留了它。根据上面的表结构,它主要是这样的:国家到城市是一对多,city_id必须是唯一的,ips是只与city_id有关系。我认为,这将是一个更好的设计......

然后,如果你必须根据你当前的表来解决问题。您将创建一个唯一的 key “UNIQUE KEY uniq_from_to (ip_from,ip_to)”;并且,有sql:

 INSERT IGNORE ip_relation  
(SELECT cA.country_id,cA.city_id,ip.ip_from,ip.ip_to FROM ip2location_db11 ip
LEFT JOIN (SELECT cy.country,ct.city,ct.country_id,ct.city_id FROM d_country cy,d_cities ct WHERE cy.country_id = ct.country_id) as cA ON ip.city_name = cA.city AND ip.country_name = cA.country);

这意味着:1.查找所有城市-国家组;然后根据城市-国家组;2.插入到第四个表中,当 ip_from-ip_to 重复时,将覆盖之前的数据。

希望能给您带来一些帮助。

关于mysql - 如何使用从 3 个连接表返回的数据填充表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20244491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com