gpt4 book ai didi

mysql - 左连接给出更多结果

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

我有这个查询:

SELECT wc.city, wc.country_id, wc.latitude, wc.longitude FROM 
world_cities wc
-- left join states s on wc.country_id = s.country_id
where wc.city = 'rosemount'

这样我得到了 6 个结果(我想要的),如果我取消注释第三行,我会得到 150 个结果。为什么当我取消注释第 3 行时我会得到更多结果,难道我不应该仍然只得到 6 个结果吗?我觉得我在这里错过了一些东西......

mysql> describe states;
+------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------------+------+-----+---------+----------------+
| state_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| country_id | tinyint(3) unsigned | YES | | NULL | |
| state_name | char(15) | YES | | NULL | |
+------------+---------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

世界城市

mysql> describe world_cities;
+-------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+----------------+
| city_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| state_id | int(11) | YES | | 0 | |
| country_id | tinyint(3) unsigned | YES | MUL | NULL | |
| country | char(2) | YES | | NULL | |
| city | char(60) | YES | MUL | NULL | |
| accent_city | char(60) | YES | | NULL | |
| region | int(11) | YES | | NULL | |
| population | int(11) | YES | | NULL | |
| latitude | decimal(9,6) | YES | | NULL | |
| longitude | decimal(9,6) | YES | | NULL | |
+-------------+---------------------+------+-----+---------+----------------+
9 rows in set (0.01 sec)

编辑
我现在已经运行了这个,它很好地更新了 world_cities 表中的 state_id。

update world_cities wc 
left join zipcodes z on wc.city = z.city
left join cities c on z.state = c.city_name
left join states s on z.state = s.state_name
set wc.state_id = s.state_id
where wc.country_id = 236
and abs(round(z.lat, 2) - round(wc.latitude, 2)) between 0 and 1
and abs(round(z.log, 2) - round(wc.longitude, 2)) between 0 and 1;

最佳答案

您在 world_cities 中有 6 条记录,其中城市为“rosemount”,但您有许多个州与这些城市属于同一个国家/地区。例如,美国密歇根州底特律与美国所有其他州是同一个国家。因此,在我的示例中,我希望得到类似 300 = 6 * 50 的结果。

您很可能想加入另一个条件:wc.country_id = s.country_id AND wc.state_id = s.state_id。查看您的架构,无法识别城市属于哪个州。您需要创建一个 world_cities.state_id 列。

关于mysql - 左连接给出更多结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15593175/

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