有一个Postgres数据库,该表有三列。
每一行代表一个对象:
key value element_id
--------------------------------
status active 1
name exampleName 1
city exampleCity 1
我想从value
行中获取每一列key=name
,如果该元素在active
行中具有key=status
值。
在此示例中,结果应为exampleName
,因为此元素为active
。我试图加入,但不打算怎么解决。你能帮我吗?
答案 0 :(得分:1)
根据我的理解,我认为您想要这样做:
尝试:
quantz=> select * from maya;
key | value | element_id
--------+-------------+------------
status | active | 1
name | exampleName | 1
city | exampleCity | 1
(3 rows)
Select value
From maya
WHERE key = 'name'
and element_id in (Select element_id from maya where key='status' and value='active')
;
value
-------------
exampleName
(1 row)
让我知道这行不通吗?
答案 1 :(得分:1)
为此,您应该将表与自身连接:
SELECT names.value
FROM mytable AS names
JOIN mytable AS statuses USING(element_id)
WHERE names.key = 'name'
AND statuses.key = 'status'
AND statuses.value = 'active'