SQLite列名歧义报错:Pandas关联表时t2.AGENT_INFOstager异常
问题分析与解决
你报错的核心原因是重复使用了同一个表别名t2:你连续三次关联init表,但每次都用t2作为别名,SQL引擎无法区分这三个不同的t2实例,自然会认为t2.AGENT_INFOstager这个列名是模糊的。
另外你的SQL写法存在冗余——你不需要三次关联init表,应该把三个关联条件合并到同一个INNER JOIN的ON子句里,这样只需要关联一次init表,用唯一的别名即可。
修正后的代码如下:
conn = sqlite3.connect(':memory:') otvetili.to_sql('otvetili', conn, index=False) init.to_sql('init', conn, index=False) query = ''' select t1.date, t1.ABONENT, t1.CONNID, t1.AGENT_INFsv, t1.NAMEsv, t1.Date_Time_Agent, t1.Date_Time_End, t2.AGENT_INFOstager, t2.NAMEstager, t2.Date_Time_Agent1inc, t2.Date_Time_End1inc from otvetili t1 INNER join init t2 on t1.CONNID = t2.CONNID and t1.Date_Time_Agent > t2.Date_Time_Agent1inc and t1.Date_Time_Agent < t2.Date_Time_End1inc ''' df = pd.read_sql_query(query, conn)
如果确实需要多次关联init表(比如关联不同维度的行数据),必须给每个关联的表分配不同的别名,查询时明确指定对应的别名,示例如下:
select t1.date, t2.AGENT_INFOstager, t3.AGENT_INFOstager from otvetili t1 INNER join init t2 on t1.CONNID = t2.CONNID INNER join init t3 on t1.other_column = t3.other_column
内容的提问来源于stack exchange,提问作者Hellobrine
相关产品推荐
相关产品推荐

