[英]SQL query in MySQL containing mathematical comparison
I need to have a SQL that finds values from table B using (randomize) values on table A in comparative manner. 我需要一个SQL,以比较的方式使用(随机)表A上的值从表B中查找值。 Table A values has been produces in randomize manner.
表A的值已经以随机方式产生。 Table B values have been order in a way of cumulative distribution function.
表B值已按照累积分布函数的方式进行排序。 What is needed is that SQL will get the first row from table B which satisfy the criteria.
需要的是,SQL将从表B中获得满足条件的第一行。
Table A: +----+-------+ | ID | value | +----+-------+ | 1 | 0.1234| | 2 | 0.8923| | 3 | 0.5221| +----+-------+ Table B: +----+-------+------+ | ID | value | name | +----+-------+------+ | 1 | 0.2000| Alpha| | 2 | 0.5000| Beta | | 3 | 0.7500| Gamma| | 4 | 1.0000| Delta| +----+-------+------+ Result should be: +----+-------+------+ | ID | value | name | +----+-------+------+ | 1 | 0.1234| Alpha| | 2 | 0.8923| Delta| | 3 | 0.5221| Gamma| +----+-------+------+
Value 0.1234 is smaller than all the values of B, but Alpha has smallest value. 值0.1234小于所有B值,但是Alpha值最小。
Value 0.8923 is smaller than 1.000 --> Delta. 值0.8923小于1.000->增量。
Value 0.5221 is smaller than both 0.7500 and 1.000 but 0.7500 is smallest --> Gamma. 值0.5221小于0.7500和1.000,但0.7500最小->伽玛。
This query works only if table A has one value: 仅当表A具有一个值时,此查询才有效:
select value, name from B where (select value from A) < value;
Any ideas how to get this work with full table A? 有什么想法如何使全表A正常工作吗?
You can use subquery to get the data you need: 您可以使用子查询来获取所需的数据:
SELECT a.ID, a.value,
(SELECT b.name FROM TableB b WHERE a.value < b.value ORDER BY b.ID ASC LIMIT 1) as name
FROM TableA a
In this case for each row in table A you find the first record in table B, that has larger number in column value
. 在这种情况下,对于表A中的每一行,您都会在表B中找到第一条记录,该记录的列
value
数字更大。 Depending on your requirements the operator <
might beed to be updated to <=
- it depends on your requirements 根据您的要求,操作员
<
可能会被更新为<=
-这取决于您的要求
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.