简体   繁体   English

如何在MySQL中处理复杂的条件where子句

[英]How to handle complex conditional where clauses in mysql

Based on a variety of optional user inputs, I need to modify the structure of the where clause in query (not just dynamic values, but dynamic structure). 基于各种可选的用户输入,我需要修改查询中where子句的结构(不仅是动态值,而是动态结构)。
Examples.. if they select a customerID, then don't use the branchID filter, but if they select an empID then use both empID and branchID filters. 例如..如果他们选择一个customerID,则不要使用branchID筛选器,但是,如果他们选择empID,则请同时使用empID和branchID筛选器。 There are more criteria that are used as well, thats just an example. 还使用了更多标准,这只是一个示例。

I could build all the logic into the where clause using CASE statements, but I'm guessing that wouldn't be very well optimized? 可以使用CASE语句所有逻辑构建到where子句中,但是我猜想它不会得到很好的优化吗? I know I could dynamically build the sql statement within a stored proc, and i could use prepared statements as well... but that seems sloppy? 我知道我可以在存储的proc中动态构建sql语句,也可以使用准备好的语句...但这似乎草率? Is there another method I'm not thinking of? 我还有别的方法吗?

The usual approach is dynamically building the query in the layer that handles the user input. 通常的方法是在处理用户输入的层中动态构建查询。 In case you do not use a high level language in front of your database, this means resorting to a stored procedure indeed, and this might look a bit dirty indeed - I too find this language quite awkward. 如果您没有在数据库之前使用高级语言,这意味着确实使用了存储过程,并且这看起来确实有点脏-我也觉得这种语言很尴尬。

A pure SQL solution does not have too much of an overhead, since constant-based conditions will be optimized away quite efficiently (user input is constant when the query starts). 纯SQL解决方案没有太多的开销,因为可以非常有效地优化基于常量的条件(查询开始时用户输入是常量)。

I have typically done what you are doing using bind variables and a conditional query, like so: 我通常使用绑定变量和条件查询来完成您的工作,例如:

SELECT ...
FROM table
WHERE ...(put your where clause elements common to both cases here)
AND ((? = 'value1'
       AND ...
       AND ...
    ) OR
    (? = 'value2'
       AND ...
       AND ...
    ))
GROUP BY ...
ORDER BY ...

? is the bind variable syntax for MySQL -- see Listing 23 here for a small example. 是MySQL的绑定变量语法-参见清单23 在这里的一个小例子。 In this case, bind vars 1 and 2 would actually be set to the same value. 在这种情况下,绑定变量1和2实际上将设置为相同的值。

You can also do the same sort of thing with a CASE statement. 您还可以使用CASE语句执行相同的操作。

mybatis dynamic sql may helps you。 mybatis动态sql可能会帮助您。

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

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

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