在不起作用时按顺序使用 table

Use table in order by case when does not work

我是运行这个查询但是我得到一个错误

select *
from dog
order by case
             when exists(
                     select 1 from dogfood where dog.dogid = dogfood.dogid)
                 then '1'
             else '0' end;

所以 2 tables,dogdogfood 都有一个 dogid 列。我收到此错误:

[42703][-206] "DOG.DOGID" is not valid in the context where it is used.. SQLCODE=-206, SQLSTATE=42703, DRIVER=4.26.14 [56098][-727] An error occurred during implicit system action type "2". Information returned for the error includes SQLCODE "-206", > SQLSTATE "42703" and message tokens "DOG.DOGID".. > SQLCODE=-727, SQLSTATE=56098, DRIVER=4.26.14

如果狗在 dogfood 中有一行,我只想按它来排序。一种解决方案是在 select 子句中查询结果并在 order by 子句中引用它,但我希望它在我的应用程序的 order by 子句中。我很好奇为什么这个查询不起作用,我仔细检查了语法错误,但找不到任何语法错误。我错过了一些明显的东西吗?我希望我可以按照我在 select/from 子句中查询的顺序引用 table。

documentation

sort-key-expression An expression that is not simply a column name or an unsigned integer constant. The query to which ordering is applied must be a subselect to use this form of sort-key. The sort-key-expression cannot include a correlated scalar fullselect (SQLSTATE 42703) or a function with an external action (SQLSTATE 42845).

但由于它不相关,您可以将 IN 与全查询一起使用

select *
from dog
order by 
  case when dog.dogid in (select dogid from dogfood)
      then '1' else '0' end;