Question

I'll try to explain it as simple as possible:

First some database structure with dummy data.

Structure

tb_spec_fk

feature     value
-----------------
1           1
1           2
1           3
1           4
1           5
2           2
2           3
3           1
3           4
4           2
4           3
4           4
5           1
5           3
5           5
6           3
6           5

tb_spec_feature

feature_id  filter
------------------
1           2
2           2
3           2
4           2
5           1
6           0

tb_spec_value

value_id    name
----------------
1           10
2           20
3           30
4           40
5           50

Now, what I want is the follow result

Result

feature_id  min_value   max_value
---------------------------------
1           10          50
2           20          30
3           10          40
4           20          40

But how?

Logic

Get from the tb_spec_feature where "filter" equals 2 the highest and lowest values which are present in the tb_spec_value table and connected together trough the tb_spec_fk table.

My attemps

A lot! But I'll spare you :)

Was it helpful?

Solution

SELECT
    f.feature_id AS feature_id,
    MAX(value.name) AS max_value,
    MIN(value.name) AS min_value
FROM tb_spec_feature AS f
    JOIN tb_spec_fk AS fk ON f.feature_id=fk.feature
    JOIN tb_spec_value AS value ON fk.value=value.id
WHERE f.filter=2
GROUP BY f.feature_id

The two JOIN statements "link" the a feature to a value. GROUP BY groups all rows with the same feature id, and then you can take the min or max or any other aggregate function on those columns.

Demo

OTHER TIPS

Here is how you can do it

select 
    tsf.feature_id,
    tsvl.name as Min_Value,
    tsvr.name as Max_Value
from tb_spec_feature as tsf
inner join (select feature , MIN(value) MinV,MAX(value)MaxV from tb_spec_fk group by feature order by feature)as tsfkl on tsfkl.feature = tsf.feature_id
left join tb_spec_value as tsvl on tsvl.value_id = tsfkl.MinV
left join tb_spec_value as tsvr on tsvr.value_id = tsfkl.MaxV
where tsf.filter = 2
group by tsf.feature_id

Output

feature_id  | Min_Value | Max_Value
---------------------------------
1           |   10      |   50
2           |   20      |   30
3           |   10      |   40
4           |   20      |   40

Fiddle Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top