I’m trying to create a trigger, where inserted certain value in column if one value "currentAttemptCount" becomes equal or more to another "attemptCountLimit" from another table
i have two tables
@Table(name = "course_items")
public class CourseItem {
@Id
@Column(name = "course_item_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "attempt_count_limit")
private Integer attemptCountLimit;
@Table(name = "work_course_items")
public abstract class WorkCourseItem {
@Id
@Column(name = "work_course_item_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
@Enumerated(EnumType.STRING)
protected CourseItemState state;
@ManyToOne
@JoinColumn(name = "course_item_id", referencedColumnName = "course_item_id")
protected CourseItem courseItem;
@Column(name = "current_attempt_count")
protected Integer currentAttemptCount;
and how should i compare those values? trying something like next, because INNER JOIN doesn’t seem necessary in trigger
IF ((SELECT attempt_count_limit
FROM "ts".course_items
WHERE course_items.course_item_id = new.course_item_id) <=
(SELECT current_attempt_count
FROM "ts".work_course_items
WHERE work_course_items.work_course_item_id = new.work_course_id))
THEN
UPDATE "ts".work_course_items
SET state = 'YEAP_IT_IS'
WHERE work_course_item_id = new.work_course_item_id;
END IF;
RETURN new;
END;
$$ LANGUAGE PLPGSQL;
CREATE OR REPLACE TRIGGER quiz_attempt_count
BEFORE UPDATE OF state
ON "ts".work_course_items
FOR EACH ROW
EXECUTE PROCEDURE change_work_course_state();
2
Answers
Here is how you can compare two col from diff tbs
PL/pgSQL Example:
You have an update event that happens when a
work_course_items
record is being updated. So, you have a single record from this table to operate with inside yourtrigger
. Hence, yourIF
is superfluous:Instead of the second query, you could simply pass
new.current_attempt_count
to your `procedure, because you already have that value in the trigger.As about your first query, its logic is correct.
You will need to actually try anything that you implement and make sure that it works properly though.