简体   繁体   English

使用 2 where 条件将记录插入 postgres 数据库

[英]inserting a record into postgres database using 2 where conditions

I'm trying to insert data into a table based on whether a record exists with the same ID and DATE.我正在尝试根据是否存在具有相同 ID 和 DATE 的记录来将数据插入表中。 I've put the code in a loop that does the insertion query for every record in the students_present variable.我已将代码放在一个循环中,该循环对 students_present 变量中的每条记录执行插入查询。 HERE'S THE CODE这是代码

for ID in students_present:
    STUDENTID = 'SELECT STUDENTID FROM encodings WHERE STUDENTID = ID'
    STUDENTNAME = 'SELECT STUDENTNAME FROM encodings WHERE STUDENTID = ID'
    STUDENTEMAIL = 'SELECT STUDENTEMAIL FROM encodings WHERE STUDENTID = ID'
    insert_script = "INSERT INTO meeting1(STUDENTID, STUDENTNAME, STUDENTEMAIL, MEETINGDATE, MEETINGTIME) WHERE ID IN STUDENTID AND MEETINGDATE <> GETDATE() VALUES ('{}','{}','{}','GETDATE()','CURRENT_TIMESTAMP')".format(STUDENTID, STUDENTNAME, STUDENTEMAIL)
    cur.execute(insert_script)

I believe my error arrises from how I've written the condition as it reflects this error:我相信我的错误来自我编写条件的方式,因为它反映了这个错误:

syntax error at or near "WHERE"
LINE 1: INSERT INTO meeting1 WHERE ID IN STUDENTID AND MEETINGDATE <...

Any advice on how to go about this?关于如何解决这个问题的任何建议?

I created a Unique constraint key for the particular columns that I wanted to be unique by running我为我希望通过运行唯一的特定列创建了一个唯一约束键

ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2);

This will create a key that is a combination of column1 and column2 for which a record cannot exist with the same values in both columns.这将创建一个键,该键是 column1 和 column2 的组合,其中不能存在两列中具有相同值的记录。

for example if column1 is named Month and column2 named Year, I can only have one record like May 2022 for the Month and Year columns respectively.例如,如果 column1 命名为 Month,column2 命名为 Year,我只能分别为 Month 和 Year 列创建一条记录,例如 May 2022。 Once I enter another record with both month and year as May 2022 I'll get a duplicate key error on that constraint.一旦我输入另一条记录,将月份和年份都设置为 2022 年 5 月,我将在该约束上收到重复键错误。

I hope this helps someone.我希望这可以帮助别人。

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

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