Python MySQL比较两个表

2024-06-01 08:17:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想学习如何比较两个表,以便找到不匹配的记录。在

我完全是MySQL的初学者,因此目前正在努力寻找用于比较两个表的查询。在

假设我有两个结构相同的表。在

表1(旧)

+------+--------+---------------+--------+-----------+
| "id" | "name" | "price" | "description" | "country" |
+------+--------+---------------+--------+-----------+
| "1"  | "a"    | "2"     | "Lord "       | "US"      |
| "2"  | "b"    | "3"     | "Taker"       | "UK"      |
+------+--------+---------------+--------+-----------+

表2(新)

^{pr2}$

表1保存过时的数据,表2保存最新的数据。在

我想检查表2中的name、price、description字段是否与表1中的name、price、description字段匹配。如果没有,它应该用表2中的数据更新表1。在

我查看了folling站点,以了解使用哪个Mysql查询: http://www.mysqltutorial.org/compare-two-tables-to-find-unmatched-records-mysql.aspx

但是我不知道如何用Python写下来。在

我不熟悉在python中使用SQL语句,并尝试将其作为

 import sys, mysql.connector
 import mysql

 try:
     connection = mysql.connector.connect\
         (host = "localhost", user = "root", passwd ="", db = "local")
 except:
     print("No connection")
     sys.exit(0)

 cursor = connection.cursor()
 cursor.execute("SELECT name, price, description FROM table2_new WHERE 

我真的不知道该怎么继续下去了。我搜索过类似的任务,但不完全理解如何用Python完成它。在

这是表1所需的产量,价格应更新:

    +------+--------+---------------+--------+-----------+
    | "id" | "name" | "price" | "description" | "country" |
    +------+--------+---------------+--------+-----------+
    | "1"  | "a"    | "5"     | "Lord "       | "US"      |
    | "2"  | "b"    | "6"     | "Taker"       | "UK"      |
    +------+--------+---------------+--------+-----------+

你们能帮帮我吗?欢迎任何反馈。在


Tags: 数据nameimportidsysmysqldescriptionconnection
3条回答

您的SQL查询将大致如下:

UPDATE t1
SET t1.name = t2.name
from table1 as t1
inner join table2 as t2
on t1.id = t2.id
AND t1.name != t2.name

然后对每个字段重复此操作。在

首先,表绑定的是哪个字段?我们把它命名为bind_field。如果有多个字段,那么它将是bind_field1bind_field2和其他字段。您的疑问:

UPDATE table1 t1
INNER JOIN table2 t2
ON t1.bind_field = t2.bind_field [AND t1.bind_field1 = t2.bind_field2 ...]
SET t1.name = t2.name, t1.price = t2.price, t1.description = t2.description

查询只更新table1namepricedescription中的值来自table2的行,这些行具有相同的bind_field(-s,如果有多个绑定字段)。在

ON语句允许您如何绑定表。 SET语句允许您控制更新值。在

在我看来,您使用的是文本(VARCHAR或相同的)类型字段,如果是这样,那么您应该将其更改为数字类型字段,如INTEGER

另外,对不起我的英语:)

尝试

update table_1 a
join table_2 b
on a.`name` = b.`name` and a.`description` = b.`description`
set a.`price` = b.`price`

演示sqlfiddle

如果 descriptionname匹配。(当心不止一场比赛会产生你期望的结果)

相关问题 更多 >