Rob
Rob

Reputation: 69

MySQL Query max issue

I have a query that that works fine as long as there exists values in it after the WHERE condition is called. However, in some cases the query is empty because no values = '$project_id'. In this scenario it enters a blank field to the table. I would like to enter 1 by default if no values meet the WHERE condition.

Here is my query

$query = 
"INSERT INTO tapp_contact_list 
  (id, location) 
SELECT (MAX(id)+1), '$location' 
FROM tapp_contact_list
WHERE meeting_project_id = '$project_id'
";

Any help is gladly appreciated!

Upvotes: 0

Views: 43

Answers (1)

peter.petrov
peter.petrov

Reputation: 39477

Try this.

$query = 
"INSERT INTO tapp_contact_list 
  (id, location) 
SELECT COALESCE( (MAX(id)+1), 1 ) , '$location' 
FROM tapp_contact_list
WHERE meeting_project_id = '$project_id'
";

For more details check this function.

http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce

Upvotes: 1

Related Questions