In mysql, I tried to print ‘-1’ if 3 conditions are satisfied.
SELECT '-1'
WHERE not exists(select * from acq_staff where acq_person_id = staffID)
OR not exists(select * from acq_training_course_session where training_course_id = course_id)
OR exists(select * from acq_training_enrolment where acq_staff_acq_person_id = staffID);
But how can I change this SELECT statement to IF statement so that if either those 3 conditions are satisfied, print -1 otherwise I am going to insert a data.
Sorry for not enough information
4
Answers
I guess you can do something like this: How can I simulate a print statement in MySQL?
and just instead of
some text
set-1
.And one more thing i noticed in your question, that part "if those 3 conditions are satisfied" if you want all 3 conditions to be satisfied you need to change
OR
toAND
. Because in your case, withOR
, there needs to be satisfied only 1 condition, but withAND
all 3 of them need to be satisfied.MySQL
INNER JOIN
, along withWHERE NOT EXISTS
, can be used to determine if there’s an existing course, and existing staff, and that staff is enrolled in that course, and if not,INSERT
the staff and course id in the enrollment table.Try it here: https://onecompiler.com/mysql/3yk7xynkg
maybe you can try that
The question is about how to conditionally execute an insert query. In pseudo-code, the question asks how to do the following
Now think about it this way
or simply
INSERT INTO ... (SELECT ... WHERE <all the conditions are met>)
When
<all the conditions are met>
, the insert will actually have something to insert. Otherwise, it will have an empty result set so no rows will be inserted.So use
INSERT INTO ... SELECT ... WHERE <all the conditions are met>
Syntax to achieve desired results. Unfortunately, this solution does not have a way to return back -1.