0

我有这张桌子:

表(fied1 int,field2 int,field3 varchar(40));

我想在没有存储过程的情况下使用,例如:

declare int nr default 0;
select coalesce(max(field1),0) into nr from table where field2=? and field3=?;
if(nr = 0) then
  select coalesce(max(field1),0)+1 into nr from table;
end if;

我想从单选中获得 nr 的值。请帮忙!!!

4

2 回答 2

0

我认为这符合您的要求:

SELECT
  CASE
    WHEN (max(field1) IS NULL OR max(field1) = 0) AND field2=? AND field3=? THEN (max(field1)+1)
    ELSE max(field1)
  END AS `field1_max`
FROM table
于 2012-04-30T13:40:21.367 回答
0

Only use the following query to get one plus to last inserted value in field1 column if no match found as per where clause else it returns the max value stored in field1:

This query is handling the case if there are no records in table.

the filter crieteria "and field1<>0" in following statement is required if field1 can have value 0 also otherwise remove this filter (and field1<>0) from following query

Select coalesce(
   max(field1),
   (select coalesce(max(field1),0)+1 from table)
   ) 
from table where field2=? and field3=? and field1<>0;
于 2012-04-30T13:01:02.257 回答