SELECT DISTINCT值 - 具有相同ID的多行 - 多个条件

时间:2014-06-02 10:03:33

标签: mysql select distinct

这是我的起点:

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
  • 的所有用户
  • ORDER BY test1_score ASC

似乎相当挑战......

甚至可以使用一个查询吗?

在此示例中,结果应该是具有User_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              |

非常感谢任何帮助。

谢谢!

2 个答案:

答案 0 :(得分:2)

这是我要做的事情

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;

sqlfiddle

答案 1 :(得分:1)

这对你有用吗?

SELECT A.USER_ID, 
       A.VALUE AS "NAME", 
       B.VALUE AS "TEST1_SCORE", 
       C.VALUE AS "TEST2_SCORE"
FROM MYTABLE A, MYTABLE B, MYTABLE C
WHERE A.USER_ID = B.USER_ID
  AND A.USER_ID = C.USER_ID
  AND A.FIELD_KEY = 'name'
  AND B.FIELD_KEY = 'test1_score'
  AND B.VALUE >= 7
  AND C.FIELD_KEY = 'test2_score'
ORDER BY 3 ASC
;