我有一个根据不同 ID 获取结果的查询, 我的查询如下所示: 我已经缩短了查询,但还有两个 WHERE In 条件。
SELECT DISTINCT restaurant.*,branch.*
from restaurant,branch,restaurant_cuisines,restaurant_collections
WHERE restaurant.restaurant_id=branch.restaurant_id
AND restaurant_cuisines.cuisine_id IN (2,3)
AND restaurant_collections.collection_id IN ();
当条件中第二个 WHERE 没有值时如何执行此查询? 或如何在应用程序级别(Java)中处理此问题,我需要编写大约 28 个 if else 条件来检查空条件。如何克服这个问题?
最佳答案
这完全取决于您的需求。通常你应该跳过整个部分。
当您对所有条件使用 AND
时,我假设您希望通过空列表返回所有行。(我猜最终用户有某种类型的多个复选框或类似的东西)。
如果列定义为 NOT NULL
,您可以像这样在 JAVA 中生成代码:
...
AND restaurant_collections.collection_id IN(restaurant_collections.collection_id)
-- which is always true and good query optimizer should skip entire part
当您需要特定值时,您可以像以前一样使用它:
...
AND restaurant_collections.collection_id IN (1,2,3)
关于java - where in 子句中没有值时如何执行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084972/