有两张table:
参考:
id | score | value | type_id
1 | 0 | 10 | 1
2 | 1 | 20 | 1
3 | 2 | 30 | 1
.. | .. | .. | ..
字符串
结果:
id | score | type_id
1 | 2 | 1
2 | 7 | 2
3 | 0 | 3
型
我想根据result
表中的score
,从refernce
表中为每个type_id
获取value
。
查询:
SELECT ref.score, ref.value, ref.type_id
FROM `refernce` ref
JOIN `result` res
ON ref.type_id = res.type_id
WHERE res.score >= ref.score
GROUP BY ref.type_id
ORDER BY ref.id DESC;
型
在这种情况下,输出应该是:
score | value | type_id
0 | 8 | 3
3 | 25 | 2
2 | 30 | 1
型
但这是实际输出:
score | value | type_id
0 | 8 | 3
0 | 5 | 2
0 | 10 | 1
型
因此,如果result
表中的score
存在于refernce
中,则此分数的value
,并且如果result
表中的score
大于refernce
表中的value
,则应返回大于score
的value
,即3。
这是一把小提琴:http://sqlfiddle.com/#!9/ecf 1 e3/1
2条答案
按热度按时间dbf7pr2w1#
使用MAX:)获取最大值...然后基于这两个值再次加入...
字符串
如果你使用的是一些更复杂的数据库(Postgre,Oracle,...)
您可以使用窗口函数来分区和排序行..然后只在随后的筛选中选择您需要的行
示例(未测试)
型
2o7dmzc52#
只使用一个子查询的解决方案,来自链接
reference
和result
数据表,其中score
和value
数据行会转换成固定长度的十六进制字串表示,然后加以组合,并套用max
汇总函数,再将十六进制字串转换回整数。字符串
测试结果:
型
SQL小操作。