简体   繁体   English

使用if条件where子句的M​​ySQL查询

[英]MySQL query with if condition where clause

I have table ORDERS with id, appId, status, orderId. 我有ID,appId,status,orderId的表ORDERS。

status can - OK, ONHOLD, DONE, REJECT etc 状态可以-OK,ONHOLD,DONE,REJECT等

 For this use case i want to filter with status OK and ONHOLD and order if status is "OK" - I want to get allow all orderIds if status is "ONHOLD" - only get ids with whiteList orders. Here the statusList has 2 Strings and whiteListOrders dynamically generated list 
 public List<Long> getIds(
   @Bind("appId") String appId,
   @BindIn("statusList") List<String> statusList,
   @BindIn("whiteListOrders") List<String> whiteListOrders);

How to achieve this in mysql query 如何在mysql查询中实现

Below would be the generic query - 以下是一般查询-

SELECT <req cols> 
FROM   mytable1 
WHERE  status='OK' 
UNION 
SELECT <req cols> 
FROM   mytable 
WHERE  status='ONHOLD' 
AND    id IN 
       ( 
              SELECT orderids 
              FROM   <whitelistorders>)

If you can provide the table and column details, you can do it with join as well. 如果您可以提供表和列的详细信息,则也可以使用join来完成。

Hope this helps. 希望这可以帮助。

You could union the queries. 您可以合并查询。 This will give you the data you want. 这将为您提供所需的数据。

(SELECT ids FROM ORDERS WHERE status='OK' AND ids IN (@whiteListIds))
UNION  
(SELECT ids FROM ORDERS WHERE status='ONHOLD' AND ids IN (@whiteListIds))

As mentioned, this would be possible without the UNION : 如前所述,如果没有UNION ,这将是可能的:

#set @whitelist = your whitelist IDS; /* Not sure how you have this setup */
SELECT 
  * 
FROM 
  user 
WHERE 
  status='OK' 
  OR (
    status='ONHOLD' 
    AND id IN (@whitelist)
  )

Hope this helps, 希望这可以帮助,

Neither of the supplied answers is optimal, as they both use a UNION. 提供的答案均不是最佳答案,因为它们都使用UNION。 There is no reason whatsoever to do this, you can easily add whatever multiple clauses you need by combining clauses inside your WHERE clause using a combination of AND, OR and parenthesis. 完全没有理由这样做,您可以使用AND,OR和括号将WHERE子句中的子句组合在一起,从而轻松添加所需的多个子句。

I'd also consider using and exists(subquery) rather than using in (subquery) 我也会考虑使用and exists(subquery)而不是in (subquery)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM