我在 MySQL 中有一个表,如下所示。
+---------+------------+--------------+
| user_id | key | value |
+---------+------------+--------------+
| 1 | full_name | John Smith |
+---------+------------+--------------+
| 1 | is_active | 1 |
+---------+------------+--------------+
| 1 | user_level |Administrator |
+---------+------------+--------------+
我需要获取 full_name 的值,其中 user_id 是 1,但前提是键的值 is_active 是 1。我可以用 2 个单独的查询来完成,但我想知道是否可以在单个查询中完成。
注意:我无法更改表的结构。
最佳答案
一种方法是使用join
:
select tn.value
from t tn join
t ta
on tn.user_id = ta.user_id and ta.key = 'active'
where tn.key = 'fullname';
关于MySQL查询基于另一个查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52890976/