从可用的 M 个条件中选择至少满足 N 个条件的一个
有一个问题浮出水面。它是用基本 SQL 术语设置的,但其本质是纯数学(所以也许我也应该访问 https://mathoverflow.net)。
我在一些理论数据库中有一个表,有 6 个字段,全部都是数字。另外我们还有基本条件,比如 Field_1 > Field_5、Field_4 = 3 等,总共 7 个条件。我需要编写一个选择,它至少满足其中4个。
编写具有许多逻辑条件的长选择,例如 (cond_1 AND cond_2 AND cond_3 and cond_4) OR (...) 不是一种方法,因为 7 个元素的 4 组合等于 140,而一个不想写那么多条件。
那么如何以简化形式编写选择呢?
there is a question floated. It's set in basic SQL terms, but its nature is pure math (so maybe I should visit https://mathoverflow.net too).
I have a table in some theoretical database with 6 fields, all are numbers. Also we have basic conditions, such as Field_1 > Field_5, Field_4 = 3 etc., 7 conditions total. I need to write a select, which satisfies at least 4 of them.
Writing long select with many logical conditions such as (cond_1 AND cond_2 AND cond_3 and cond_4) OR (...) is not a way, because 4-combination from 7 elements is equal to 140, and one doesn't want to write so many conditions.
So how do I write a select in its simplified form?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种方法是为该行满足的每个条件计数 1,并将总和与目标值进行比较:
请注意,这将需要评估每行的所有条件,这样您就不会得到短路效应,但是它很简单,也许它的性能适合您。
如果您使用 MySQL,您可以以更简单的方式编写此代码,因为布尔结果相当于 0 或 1,因此您不需要 CASE 语句:
One way of doing it is to count 1 for each condition that the row satisfies and compare the sum to your target value:
Note that this will require evaluating all the conditions for each row so you won't get a short-circuiting effect, but it's simple and maybe it has good enough performance for you.
If you're using MySQL you can write this in a much simpler way because a boolean result is equivalent to 0 or 1 so you don't need the CASE statements:
您可以简单地将真实条件的总和加在一起,然后
对 condition_sum > 进行过滤。阈值。您甚至可以将案例总和表达式的肮脏内容放入函数中,以获得稍微更具可读性的代码。
You could simply add the sum of the true conditions together, a la
and filter on condition_sum > threshhold. You could even put the nastiness of that sum-of-cases expression into a function for slightly more readable code.
我建议简单地计算满足多少个条件。特定的语法取决于您使用的数据库管理引擎,但在 MySQL 中,它看起来像这样:
I'd suggest simply counting up how many conditions are satisfied. The particular syntax will depend on which database management engine you're using, but in MySQL it would look something like this: