2014-04-29 27 views
0

我有这个查询正在工作,直到我意识到如果表为空,max不起作用。我检查一个用户的position,然后插入一个位置更高的行。我如何设置一个案例,如果没有适当的user_id的行,我插入一个位置为1的行?我试图做一个case语句,但它不起作用,我淹没在Mysql语法中。具有集合函数的Mysql case语句(仅在集合函数使用时才使用集合)

以下是原始

$stmt = $dbh->prepare(" 
    insert into 
     dashboard_data 
    (position, user_id) 
     select 
      max(position) + 1, 
      :userid 
     from 
      dashboard_data 
     where 
      user_id = :userid 
"); 

这里是我在一个case语句误导尝试

insert into 
     dashboard_data 
    (position, user_id) 
     select 
      case 
       when exists 
        max(position) 
       then 
        max(position) + 1 
       else 
        1 
      end case, 
      :userid 
     from 
      dashboard_data 
     where 
      user_id = :userid 

回答

2

使用coalesce()

insert into dashboard_data(position, user_id) 
    select coalesce(max(position), 0) + 1, 
      :userid 
    from dashboard_data 
    where user_id = :userid; 
+0

+1,我已经使用@ marshall的答案,但它的工作。 –

+0

@CraigPatrickLafferty如果您有一系列可能的NULL值,那么Coalesce会更好,否则它们的操作方式相似。 https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce –

+0

我同意,但我碰巧只有一个可能的值。我将来一定会使用它。 –