gpt4 book ai didi

postgresql - Postgres LEFT JOIN 正在创建比左表更多的行

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

我在 Windows 7 x64 上运行 Postgres 9.1.3 32 位。 (必须使用 32 位,因为没有与 64 位 Postgres 兼容的 Windows PostGIS 版本。)(编辑:从 PostGIS 2.0 开始,它与 Windows 上的 64 位 Postgres 兼容。)

我有一个查询,left 将一个表 (consistent.master) 与一个临时表连接起来,然后将结果数据插入第三个表(consistent .masternew).

因为这是一个left join,结果表的行数应该与查询中的左表相同。但是,如果我运行这个:

SELECT count(*)
FROM consistent.master

我得到 2085343。但是如果我运行这个:

SELECT count(*)
FROM consistent.masternew

我得到 2085703

masternew 怎么能比 master 多行呢? masternew 不应该与 master(查询中的左表)具有相同的行数吗?

下面是查询。 mastermasternew 表的结构应该相同。

--temporary table created here
--I am trying to locate where multiple tickets were written on
--a single traffic stop
WITH stops AS (
SELECT citation_id,
rank() OVER (ORDER BY offense_timestamp,
defendant_dl,
offense_street_number,
offense_street_name) AS stop
FROM consistent.master
WHERE citing_jurisdiction=1
)

--Here's the insert statement. Below you'll see it's
--pulling data from a select query
INSERT INTO consistent.masternew (arrest_id,
citation_id,
defendant_dl,
defendant_dl_state,
defendant_zip,
defendant_race,
defendant_sex,
defendant_dob,
vehicle_licenseplate,
vehicle_licenseplate_state,
vehicle_registration_expiration_date,
vehicle_year,
vehicle_make,
vehicle_model,
vehicle_color,
offense_timestamp,
offense_street_number,
offense_street_name,
offense_crossstreet_number,
offense_crossstreet_name,
offense_county,
officer_id,
offense_code,
speed_alleged,
speed_limit,
work_zone,
school_zone,
offense_location,
source,
citing_jurisdiction,
the_geom)

--Here's the select query that the insert statement is using.
SELECT stops.stop,
master.citation_id,
defendant_dl,
defendant_dl_state,
defendant_zip,
defendant_race,
defendant_sex,
defendant_dob,
vehicle_licenseplate,
vehicle_licenseplate_state,
vehicle_registration_expiration_date,
vehicle_year,
vehicle_make,
vehicle_model,
vehicle_color,
offense_timestamp,
offense_street_number,
offense_street_name,
offense_crossstreet_number,
offense_crossstreet_name,
offense_county,
officer_id,
offense_code,
speed_alleged,
speed_limit,
work_zone,
school_zone,
offense_location,
source,
citing_jurisdiction,
the_geom
FROM consistent.master LEFT JOIN stops
ON stops.citation_id = master.citation_id

以防万一,我运行了 VACUUM FULL ANALYZE 并重新索引了两个表。 (不确定确切的命令;通过 pgAdmin III 完成。)

最佳答案

左连接的行数不一定与左表中的行数相同。基本上,它就像一个普通的连接,只是左表中不会出现在普通连接中的行也被添加了。因此,如果右表中有不止一行与左表中的一行相匹配,则结果中的行数可能多于左表中的行数。

为了做你想做的事,你应该使用分组依据和计数来检测倍数。

select citation_id
from stops join master on stops.citation_id = master.citation_id
group by citation_id
having count(*) > 1

关于postgresql - Postgres LEFT JOIN 正在创建比左表更多的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9761959/

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