0

I am trying to write a MySQL insert that only inserts based on the result of a select query. I have found some information on using if-then-endIf logic in queries but haven't had any luck getting one to work. Then general idea that I am trying to accomplish is like:

if
 result of select is > 0
 perform insert and select true
 else select false
endIf

I want to run it this way as it seems like the easiest way to stop from inserting more than the predefined limit.

Anyway, if someone could point me in the right direction for how to structure/nest the statements I would be very grateful.

Thank you.

EDIT

in case anyone is wondering, this is what I ended up with:

insert into users_to_classes select ? , ?, 4 from (select class_id, count(*) as students from users_to_classes where participation_level=4 group by class_id) as numUtC, classes where numUtC.class_id=classes.class_id and classes.class_id=? and classes.spaces - ifnull(numUtC.students,0) > 0

where it is used as a mysqli prepared statement.

Thanks again for the help

Aaron Luman
  • 635
  • 1
  • 10
  • 29
  • Please accept my answer if it has helped you. If not, please add further information so I/we can help you further. – Fellmeister Apr 06 '11 at 01:35

1 Answers1

4

You could try this with some relevant changes:

INSERT INTO <destination_table>
   SELECT <values>
   FROM <source_table>
   WHERE <value> > x

Slight edit to make it clearer.

Fellmeister
  • 591
  • 3
  • 24
  • Wow, that was a lot easier than I had thought it out to be. Ha, thanks a ton. sorry about the delay there, i was busy with a customer issue – Aaron Luman Apr 06 '11 at 01:43
  • Don't worry about it, it's a handy little trick that's saved me a lot of time in the past. Thanks for the reply & acceptance. – Fellmeister Apr 06 '11 at 02:11