0

We have a table where we limit the number of rows per user to a certain number. Before insert, we check if user has exceeded the storage capacity (number of rows) and then insert as appropriate. For example,

select count(id) from items where user=123;

say, if count < 10,

insert into items set user=123, a=xyx;

However, this approach requires two queries. Is there a way in which is can be done in a single query.

Thanks

mesibo
  • 3,970
  • 6
  • 25
  • 43

2 Answers2

0

Pretty much any approach you take will require two queries. Whether you do this in a trigger or in application code is a matter of choice.

If you use your method, then add an index on items(user). This will make it cheap to count the number of rows.

An alternative is to increment a value in the user table for each item. So, when a user inserts an item, then increment users.itemcount. Remember, though, to reduce the count when you delete items.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

If you just want to have 1 query in a code you can try to use conditional insert with approach described here MySQL Conditional Insert

Community
  • 1
  • 1
Stan
  • 1,410
  • 10
  • 14