我有这个查询正在工作,直到我意识到如果表为空,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
曾为漂亮,我已经得到了它与10号线的垃圾工作,但由此带来下来到1 –
@CraigPatrickLafferty简单的答案通常是最好的 –