gpt4 book ai didi

sql - 如何重命名由SQL INNER JOIN获得的列?

转载 作者:行者123 更新时间:2023-12-03 18:32:41 26 4
gpt4 key购买 nike

我正在网站上阅读SQL和Pandas的比较
http://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html。在这里,当我执行sql内部联接时,列的名称会重复。如何给他们起适当的名字?

import numpy as np
import pandas as pd
import sqlite3
np.random.seed(100)


# database
con = sqlite3.connect("mydb.db")


# dataframes
df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'],
'value': np.random.randn(4)})

df2 = pd.DataFrame({'key': ['B', 'D', 'D', 'E'],
'value': np.random.randn(4)})

print(df1, '\n\n', df2)

# add dataframes to database
df1.to_sql('df1',con,if_exists='replace',index=False)
df1.to_sql('df2',con,if_exists='replace',index=False)


q = """
SELECT *
FROM df1
INNER JOIN df2
ON df1.key = df2.key;
"""
pd.read_sql_query(q,con)


这给

 key     value key     value
0 B 0.342680 B 0.981321
1 D -0.252436 D 0.221180
2 D -0.252436 D 0.514219


如何获得表,如:

    key   df1_value   df2_value
0 B 0.342680 0.981321
1 D -0.252436 0.514219
2 D -0.252436 0.221180

最佳答案

使用as

SELECT df1.key as key1, df1.value as df1_value, df2.value as df2_value
FROM df1 INNER JOIN
df2
ON df1.key = df2.key;


因为键是相同的,所以您不需要包括两个表中的值。

关于sql - 如何重命名由SQL INNER JOIN获得的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53603596/

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