[英]MySQL query with if condition where clause
我有ID,appId,status,orderId的表ORDERS。
狀態可以-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);
如何在mysql查詢中實現
以下是一般查詢-
SELECT <req cols>
FROM mytable1
WHERE status='OK'
UNION
SELECT <req cols>
FROM mytable
WHERE status='ONHOLD'
AND id IN
(
SELECT orderids
FROM <whitelistorders>)
如果您可以提供表和列的詳細信息,則也可以使用join來完成。
希望這可以幫助。
您可以合並查詢。 這將為您提供所需的數據。
(SELECT ids FROM ORDERS WHERE status='OK' AND ids IN (@whiteListIds))
UNION
(SELECT ids FROM ORDERS WHERE status='ONHOLD' AND ids IN (@whiteListIds))
如前所述,如果沒有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)
)
希望這可以幫助,
提供的答案均不是最佳答案,因為它們都使用UNION。 完全沒有理由這樣做,您可以使用AND,OR和括號將WHERE子句中的子句組合在一起,從而輕松添加所需的多個子句。
我也會考慮使用and exists(subquery)
而不是in (subquery)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.