想象以下格式的StudentDetails表
创建表查询
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行。
注意:我无法更改表结构。
使用汇总。显然,一行不能同时匹配两个值:
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
子句中完成,因为您需要合并来自不同行的值。