将值范围与另一个值范围MYSQL进行比较

时间:2016-12-21 16:18:21

标签: mysql sql

我有一张如下表格

id_indicator    id_threshold    activation_begin_value  activation_end_value

    1           121                    1                       2
    1           122                    3                       4
    1           123                    5                       6
    1           124                    6                       7 
    2           125                    10                      9
    2           126                    8                       7
    2           127                    6                       5
    2           128                    5                       4

如何获取activation_begin_value和activation_end_value值落入另一个阈值的详细信息。其中6落入id_threshold 123和124相同,跟随两行,其中5为两个id_threshold。查询输出如下:

id_indicator     id_threshold     activation_begin_value     activation_end_value

    1           123                    5                       6
    1           124                    6                       7 
    2           127                    6                       5
    2           128                    5                       4

2 个答案:

答案 0 :(得分:0)

你的意思是什么?

Select a.id_indicator     a.id_threshold     a.activation_begin_value     a.activation_end_value from table a
where 1=1 
and a.activation_begin_value in ( select activation_end_value from table )
union 
Select b.id_indicator     b.id_threshold     b.activation_begin_value     b.activation_end_value from table b
where 1=1 
and b.activation_end_value in ( select activation_begin_value from table )

答案 1 :(得分:0)

在我看来,这可以通过自我加入和一些排序来实现。 我的结果与你想要的一样。

测试数据

public static IEnumerable<ParsedValue> GetParsedValues(TComplex tComplex)
{
    yield return tComplex.AType.ParsedValue;
    yield return tComplex.BType.ParsedValue;

    foreach(var cType in tComplex.CTypes)
    {
        yield return cType.ParsedValue;
    }
}

public static IEnumerable<Action<ParsedValue>> SetParsedValues(TComplex tComplex)
{
    yield return value => tComplex.AType.ParsedValue = value;
    yield return value => tComplex.BType.ParsedValue = value;

    foreach(var cType in tComplex.CTypes)
    {
        yield return value => cType.ParsedValue = value;
    }
}

<强>查询

CREATE TABLE Table1
    (`id_indicator` INT, `id_threshold` INT, `activation_begin_value` INT, `activation_end_value` INT)
;

INSERT INTO Table1
    (`id_indicator`, `id_threshold`, `activation_begin_value`, `activation_end_value`)
VALUES
    (1, 121, 1, 2),
    (1, 122, 3, 4),
    (1, 123, 5, 6),
    (1, 124, 6, 7),
    (2, 125, 10, 9),
    (2, 126, 8, 7),
    (2, 127, 6, 5),
    (2, 128, 5, 4)
;

<强>结果

SELECT 
   table1.id_indicator
 , table1.id_threshold
 , table1.activation_begin_value 
 , table1.activation_end_value 
FROM 
 Table1 table1
INNER JOIN
 Table1 table12
ON
 table1.activation_begin_value = table12.activation_end_value
ORDER BY 
    table1.id_indicator ASC
  , table1.id_threshold ASC

请参阅演示http://sqlfiddle.com/#!9/d18f2/2