简体   繁体   English

是否应该在 UPDATE 中添加主键列?

[英]Should primary key columns be added in the UPDATE?

In the example code below, col1 and col2 are primary keys in the database!在下面的示例代码中, col1col2是数据库中的主键

My question is: should they be added in the part of the code after the ON DUPLICATE KEY UPDATE , as it is already in the code, or should they not be added ?我的问题是:是否应该将它们添加ON DUPLICATE KEY UPDATE之后的代码部分,因为它已经在代码中,还是不应该添加

Example code:示例代码:

with Dl.cursor() as cursor:
    for chunk in np.array_split(DataFrame, 10, axis=0):
        for i in chunk.index:
            cursor.execute("INSERT INTO table_example (col1, col2, col3, col4) VALUES (%s, %s, %s, %s) ON DUPLICATE KEY UPDATE col1 = col1, col2 = col2, col3 = col3, col4 = col4;", (chunk['col1'][i], chunk['col2'][i], chunk['col3'][i], chunk['col4'][i]))
                                                                                                                         # col3 = col3, col4 = col4; ... Which version is correct?
            Dl.commit()
    cursor.close()
Dl.close()

It is not necessary to update the unique key or primary so your SQL can be like this:没有必要更新唯一键或主键,因此您的 SQL 可以是这样的:

INSERT INTO table_example (col1, col2, col3, col4)
VALUES ('col1', 'col2', 'col3', 'col4')
ON DUPLICATE KEY UPDATE col3 = :col3, col4 = :col4

The SQL already knows that it is in the context of col1 and col2 as the duplicate key. SQL 已经知道它在 col1 和 col2 的上下文中作为重复键。

So for your code it should be something like:所以对于你的代码,它应该是这样的:

with Dl.cursor() as cursor:
for chunk in np.array_split(DataFrame, 10, axis=0):
    for i in chunk.index:
        cursor.execute("""
            INSERT INTO table_example (col1, col2, col3, col4) 
            VALUES (%s, %s, %s, %s) 
            ON DUPLICATE KEY UPDATE col3 = %s, col4 = %s;""", 
            (chunk['col1'][i], chunk['col2'][i], chunk['col3'][I], 
            chunk['col4'][i]), chunk['col3'][i], chunk['col4'][i]))
    Dl.commit()
cursor.close()

If you have no other unique keys that could cause the ON DUPLICATE to be executed, col1 and col2 won't change and you should leave them out.如果您没有其他可能导致执行 ON DUPLICATE 的唯一键,则 col1 和 col2 不会更改,您应该将它们排除在外。

If you do have other unique keys, you probably don't want to change col1 and col2 anyway.如果您确实有其他唯一键,您可能不想更改 col1 和 col2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM