简体   繁体   English

在mysql join,union> =和<=中计算符合条件的行

[英]counting rows matching criteria in mysql join , union >= and <=?

Select * FROM table WHERE a<=9 AND a>=4 AND b<=20 AND b>=16 AND c<=30 AND c>=26

Now I want to end up selecting from query 1 the results in which at least two of the following criteria are met. 现在,我想从查询1中选择满足至少两个以下条件的结果。

Select * FROM table WHERE a<=7 AND a>=5 AND B<=19 AND B>=17 AND C<=29 AND c>=27

Numbers could be anything, although on query 2 these are lower for the less than eqaul and higher for the bigger than equal. 数字可以是任何数字,尽管在查询2中,数字小于eqaul较低,而大于等于equal较高。

I want to be able to set the number of minimum coincidences to be met at query 2 with a number. 我希望能够用数字设置要在查询2处满足的最小巧合次数。 For example 5 coincidences must be met at query 2 to end up making a selection in query 1. 例如,在查询2处必须满足5个巧合,才能在查询1中进行选择。

This is about range and matches count, if there is an easier way to achieve this great. 如果有更简单的方法来实现这一目标,那么这就是范围和匹配计数。

尝试使用本机MySQL函数BEETWEN

SELECT * FROM t1 WHERE key_col BETWEEN '2' AND '3';

Think it is something like this you want for the second query:- 认为第二个查询需要这样的东西:

Select *, CASE WHEN a<=7 THEN 1 ELSE 0 END + CASE WHEN  a>=5 THEN 1 ELSE 0 END + CASE WHEN B<=19 THEN 1 ELSE 0 END + CASE WHEN B>=17 THEN 1 ELSE 0 END + CASE WHEN C<=29 THEN 1 ELSE 0 END + CASE WHEN c>=27 THEN 1 ELSE 0 END AS MatchCount
FROM table 
WHERE a<=7 
OR a>=5 
OR B<=19 
OR B>=17 
OR C<=29 
OR c>=27
HAVING MatchCount >= 2

Probably using the first query as a subselect instead of table. 可能使用第一个查询作为子选择而不是表。

EDIT - reading your latest response I think I misunderstood your requirement. 编辑-阅读您的最新回复我想我误解了您的要求。 However you could possibly find the differences between each values, get the absolute value of each difference and add them together to see how close / far the differences are. 但是,您可能会发现每个值之间的差异,获取每个差异的绝对值,然后将它们加在一起以查看差异有多近/远。

i think this kind of query will do your job 我认为这种查询会做好您的工作

Select 
*,
(IF(a<=7 AND a>=5,1,0) + IF(B<=19 AND B>=17,1,0) + IF(C<=29 AND c>=27,1,0))
as totalmatch
FROM table
HAVING totalmatch >=2

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

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