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

标签 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 的所有用户
  • 按 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;

sqlfiddle

关于mysql - SELECT DISTINCT 值 - 相同 ID 的多行 - 多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23991959/

相关文章:

mysql - 在一个查询 MySql 中选择插入和更新

activerecord - Rails 3.1 不同的查找和缺失属性

MySQL 8.0 Ubuntu 服务器在移动 datadir 后无法启动

php - mysql varchar字段上的条件之间

sql - 如何在 SQL Server 表中不存在的列上使用 "SELECT"条件进行 "WHERE"查询

jquery - 当最后一个当前选择更改时,如何创建新的选择行?

sqlite - 如何计算 sqlite 中每个不同值的重复项数量?

sql-server - SQL - 选择非重复列

php - 通过选择进行子查询选择

mysql - 子查询、临时表、mysql 变量或从一个表的列中获取 pos 和 neg 搜索词以查询另一个的过程