我需要在PostgreSQL中编写一个查询,该查询应与键值列的条件匹配

问题描述 投票:0回答:1

想象以下格式的StudentDetails表

Table Image with data

创建表查询

 create table studentdetails (student_id bigint,key text,value text, primary key(student_id,key));
 insert into studentdetails values (1, 'class', 'class1'),(1, 'city', 'city1'),(2,'class','class2'),(2,'city','city2'),(3,'class','class2'),(3,'city','city2');

选择查询

select distinct student_id from studentdetails where ((key = 'class') and (value = 'class2') and (key = 'city' and value = 'city2'));

我的要求是从city2和class2获取学生(即:student_id =(2,3)),但以上查询返回0行。

注意:我无法更改表结构。

sql postgresql postgresql-10
1个回答
0
投票

使用汇总。显然,一行不能同时匹配两个值:

select student_id
from studentdetails
where (key = 'class') and (value = 'class2') OR
      (key = 'city' and value = 'city2')
group by student_id
having count(distinct key) = 2;

对学生的过滤已在having子句中完成,因为您需要合并来自不同行的值。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.