MySQL-比较同一张表中的不同键和值

时间:2020-06-03 09:28:43

标签: mysql

我有一个表,其中包含不同用户的键和值。

+---------+-----------------+-------+
| user_ID | key             | value |
+---------+-----------------+-------+
| U1      | steps_total     | 6     |
+---------+-----------------+-------+
| U1      | steps_completed | 6     |
+---------+-----------------+-------+
| U2      | steps_total     | 6     |
+---------+-----------------+-------+
| U2      | steps_completed | 3     |
+---------+-----------------+-------+
| U3      | steps_total     | 6     |
+---------+-----------------+-------+
| U3      | steps_completed | 5     |
+---------+-----------------+-------+

我需要选择2个不同的键,但只比较它们的值即可输出用户是否已完成所有步骤。

+---------+-----------+
| user_ID | completed |
+---------+-----------+
| U1      | YES       |
+---------+-----------+
| U2      | NO        |
+---------+-----------+
| U3      | NO        |
+---------+-----------+

因为键和值在同一行中但在不同的列中,所以这使我很难回头。

我可以使用哪个查询获得相似的结果?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

SELECT 
    u.id, 
    CASE o1.value = o2.value
        WHEN true "YES"
        ELSE "NO"
     END as completed
FROM
    users u
JOIN
    options o1 ON o1.user_id = u.id AND o1.key = "steps_total"
JOIN
    options o2 ON o2.user_id = u.id AND o2.key = "steps_completed"