python合并mysql两张数据库表
时间: 2023-07-25 09:35:28 浏览: 219
要合并两张MySQL数据库表,可以使用以下步骤:
1. 连接MySQL数据库并选择要操作的数据库。
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
```
2. 从第一张表中获取数据。
```python
mycursor.execute("SELECT * FROM table1")
table1_data = mycursor.fetchall()
```
3. 从第二张表中获取数据。
```python
mycursor.execute("SELECT * FROM table2")
table2_data = mycursor.fetchall()
```
4. 将两张表的数据合并。
```python
merged_data = table1_data + table2_data
```
5. 创建一个新表并将合并后的数据插入其中。
```python
mycursor.execute("CREATE TABLE merged_table (column1 VARCHAR(255), column2 VARCHAR(255), column3 INT)")
for row in merged_data:
sql = "INSERT INTO merged_table (column1, column2, column3) VALUES (%s, %s, %s)"
mycursor.execute(sql, row)
mydb.commit()
```
注意,这里假设两张表的结构是相同的,如果不同,需要进行适当的调整。此外,如果两张表中包含相同的主键,需要进行去重操作。
阅读全文
相关推荐

















