这是我的起始表:
User_ID | FIELD_KEY | VALUE
11 | name | John
11 | test1_score | 9
11 | test2_score | 6
11 | test3_score | 8
11 | test5_score | 3
27 | name | Peter
27 | test1_score | 7
27 | test3_score | 3
28 | name | Nick
28 | test1_score | 6
28 | test2_score | 5
33 | name | Felix
33 | test1_score | 7
33 | test2_score | 3
如何选择以下的唯一 User_ID
条件:
- 拥有以下两项的条目的所有用户:test1_score 和 test2_score
- test1_score >= 7 的所有用户
- 按 test1_score ASC 排序
似乎是一个挑战......
甚至可以使用一个查询吗?
在此示例中,结果应该是两个用户的用户 ID:#11 和 #33。这是因为即使用户 #28 也有 test1_score 和 test2_score 条目,但仅适用于用户 #11 和 #33 test1_score >= 7。
理想情况下我会得到这样的结果:
User_ID | NAME | TEST1_SCORE | TEST2_SCORE |
33 | Felix | 7 | 3 |
11 | John | 9 | 6 |
非常感谢任何帮助。
谢谢!
最佳答案
这是我会做的
select distinct t.id, name, test1_score, test2_score from t
inner join (select id, value test1_score from t where field_key = 'test1_score' and value >= 7) t1 on (t1.id = t.id)
inner join (select id, value test2_score from t where field_key = 'test2_score' and value is not null) t2 on (t2.id = t.id)
inner join (select id, value name from t where field_key = 'name') t3 on (t3.id = t.id)
order by test1_score;
关于mysql - SELECT DISTINCT 值 - 相同 ID 的多行 - 多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23991959/